SlideShare una empresa de Scribd logo
1 de 22
Views Notwithstanding A Programmer’s guide to working with MySQL Tables in Drupal using PHP and SQL -- Srikanth Bangalore. Bangalore.srikanth@gmail.com Drupal ID: bangalos
Drupal APIs (in PHP) for: Creating a table During installation of your custom module Post installation of your custom module Inserting into table Querying the table and iterating over rows Creating a “Block” Creating an Admin “menu” (form) Creating a form
Creating a Table (during installation of custom module) hotornot.info name = Hot Or Not description = Builds A Hot Or Not Block, And Lets Users Rate Images In A Folder. package = Hot Or Not core = 6.x hotornot.module (to be populated later) hotornot.install (see next slide)
Hotornot.install <?php function hotornot_install() {   switch ($GLOBALS['db_type']) {     case 'mysql':     case 'mysqli':       // the {tablename} syntax is so multisite installs can add a prefix to the table name as set in the settings.php file db_query("CREATE TABLE {hotornot_filelist} ( file_idint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, file_pathvarchar(256) NOT NULL DEFAULT './.', present_or_notsmallint unsigned NOT NULL DEFAULT 1,           title varchar(256),           description text         ) /*!40100 DEFAULT CHARACTER SET utf8 */;"); break;   } }
Adding Another Table later function hotornot_update_1() {   switch ($GLOBALS['db_type']) {     case 'mysql':     case 'mysqli': db_query ("CREATE TABLE {hotornot_userchoice} ( file_idint unsigned NOT NULL DEFAULT 0, uidint unsigned NOT NULL DEFAULT 0, hot_or_notsmallint unsigned NOT NULL DEFAULT 0,           PRIMARY KEY (file_id, uid)         ) /*!40100 DEFAULT CHARACTER SET utf8 */;");       break;   } }
Things To Remember … db_query function accepts an SQL statement as input, and executes it.
function hotornot_repopulate() {   $path_to_files = realpath('.') . variable_get('hotornot_folder', '/sites/default/files/hotornot');   $output = "";   $isql = "UPDATE {hotornot_filelist} SET present_or_not = 0 WHERE file_id>0";   $iresult = db_query($isql);   if ($handle = opendir($path_to_files)) {     while (false !== ($file = readdir($handle))) {       if ($file != "." && $file != "..") {         $output .= "$file";         $query = "SELECT COUNT(*) FROM {hotornot_filelist} WHERE file_path = '$file'";         $num = db_result(db_query($query));         if($num) {           $isql = "UPDATE {hotornot_filelist} SET present_or_not=1 WHERE file_path = '$file'";           $iresult = db_query($isql, $file);         } else {           $isql = "INSERT INTO {hotornot_filelist} (file_path, present_or_not) VALUES ('%s', 1)";           $iresult = db_query($isql, $file); }       }     } closedir($handle);   } drupal_set_message($output); }
Things To Remember … db_query function accepts an SQL statement as input, and executes it. db_result(db_query($sql)) extracts the SINGLE value of the db_query result. variable_get function is used to get the value of a programmer-defined variable. (see later).
hotornot.module – part 1: adding the admin menu (a) <?php function hotornot_menu() {   $items = array();   $items['admin/settings/hotornot'] = array(     'title' => t('Hot Or Not'),     'description' => t('Select The Hot Or Not Image Folder'),     'page callback' => 'drupal_get_form',     'page arguments' => array('hotornot_admin_settings'),     'access arguments' => array('administer site configuration'),   );   return $items; } ….(see next slide)
hotornot.module – part 1: adding the admin menu (b) function hotornot_admin_settings() {   $form = array();   $form['hotornot_folder'] = array(     '#type' => 'textfield',     '#title' => t('The folder where all the images for the Hot Or Not are Stored'),     '#default_value' => variable_get('hotornot_folder', 'sites/default/files/hotornot'),   );   $form['hotornot_repopulate'] = array(     '#type' => 'submit',     '#value' => 'Repopulate',   );   $form['#submit'][] = 'hotornot_admin_settings_submit_handler';   return system_settings_form($form); } function hotornot_admin_settings_submit_handler(&$form, &$form_state) {   if ($form_state['clicked_button']['#id'] == 'edit-hotornot-repopulate') { hotornot_repopulate();   } }
Things to remember … Use drupal forms api to build the forms, even the Admin forms. 3 steps to having your own module’s admin settings form: Define path + form_builder_function in hook_menu(); Build your form using the forms API. Remember to wrap your form with  “system_settings_form” Do your “stuff” in the submit handler.
hotornot.module – part 2adding the block (a) function hotornot_block($op = 'list', $delta = 0, $edit = array()) {   switch ($op) {     case 'list':       $blocks[0]['info'] = t('Rate this!');       return $blocks;     case 'view':       if ($delta == 0 ) {          $block[0]['subject'] = t("Do you like ...");         $block[0]['content'] = drupal_get_form('hotornot_hotornotform');       }       return $block[$delta];   } }
hotornot.module – part 2adding the block (b) function hotornot_hotornotform(&$form_state) { $form = array();   global $user; $sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS file_title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND (filelist.file_id not in (SELECT file_id FROM {hotornot_userchoice} WHERE uid=%d)) ORDER BY RAND() LIMIT 1"; $result = db_query($sql, $user->uid);   $atleastoneexists = FALSE;   while ($row = db_fetch_array($result)) {     $atleastoneexists = TRUE;     $form['my_fileid'] = array(       '#type' => 'hidden',       '#value' => $row['file_id'] );
hotornot.module – part 2adding the block (c)   $form['picture'] = array(       '#type' => 'markup',       '#value' => '<img width="100%" src="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/><br/><strong>...'. $row['file_title'] . ' ?</strong><br/>',     );     break;   } if ($atleastoneexists) {     $form['ishot'] = array(       '#type' => 'submit',       '#value' => t('Yes')     );     $form['isnot'] = array(       '#type' => 'submit',       '#value' => t('No')     );   } else {     $form['picture'] = array(     '#type' => 'markup',     '#value' => '<p>Currently, you have seen all the items. Thank you.</p>',      );   }   return $form; }
hotornot.module – part 2adding the block (d) function hotornot_hotornotform_submit(&$form, &$form_state) {    global $user;    if ($form_state['clicked_button']['#id'] == 'edit-ishot') {        $ishot = 1;    } else {     $ishot = 0;    }    $fileid = $form_state['clicked_button']['#post']['my_fileid'];    $isql = "REPLACE INTO {hotornot_userchoice} (file_id, uid, hot_or_not) VALUES (%d, %d, %d)";    $iresult = db_query($isql, $fileid, $user->uid, $ishot); }
Things To Remember … db_query function accepts an SQL statement as input, and executes it. db_result(db_query($sql)) extracts the SINGLE value of the db_query result. To get the rows of the query result in an iterator. $result = db_query($sql);  while ($row = db_fetch_array($result)) {     $val = $row[‘column_name’] }
hotornot.module – part 3adding a page to enter title/desc (a) function hotornot_menu() {   $items = array();   // ...code... $items['hotornot/administer'] = array(     'title' => t('Hot Or Not Administration'),     'description' => t('Add Or Edit Title And Descriptions to Hot Or Not Items'),     'page callback' => 'local_hotornot_administer_description_form',     'access arguments' => array('access content'),     'type' => MENU_CALLBACK,   );   // ...code...   return $items; } function local_hotornot_administer_description_form() {   return drupal_get_form('hotornot_administer_description_form'); }
hotornot.module – part 3adding a page to enter title/desc (b) function hotornot_administer_description_form(&$form_state) {   $form = array();   global $user;   $form['blurb'] = array (     '#type' => 'markup',     '#value' => '<p>You will be shown one picture at a time that does not have any title or description. You just have to enter a title and description and hit submit.</p>' ,   );   $sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND filelist.title is NULL LIMIT 1";   $result = db_query($sql);   $atleastoneexists = FALSE;   while ($row = db_fetch_array($result)) {
hotornot.module – part 3adding a page to enter title/desc (c)  $atleastoneexists = TRUE;     $form['fileid'] = array(       '#type' => 'hidden',       '#value' => $row['file_id']     );     $form['picture'] = array(       '#type' => 'markup',       '#value' => '<imgsrc="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/>',     );     $form['title'] = array(       '#type' => 'textfield',       '#title' => 'Title',       '#default_value' => $row['title'],     );   }   if ($atleastoneexists) {     $form['submit'] = array(       '#type' => 'submit',       '#value' => 'Submit',     );
hotornot.module – part 3adding a page to enter title/desc (d)  } else {     $form['picture'] = array(     '#type' => 'markup',     '#value' => '<p>Currently, you have seen all the items. Thank you.</p>',     );   }   return $form; } function hotornot_administer_description_form_submit(&$form, &$form_state) {    $fileid = $form_state['values']['fileid'];    $title = $form_state['values']['title'];    $isql = "UPDATE {hotornot_filelist} SET title='%s' WHERE file_id=%d";    $iresult = db_query($isql, $title, $fileid); }
Summary We learnt how to create a new table at the time of installing our module How to use db_query, db_result, db_fetch_array How to create user blocks and user pages How to create Admin menus and define new variables How to use Forms API
Drupal 7 changes Switch(db_type) does not work! Db_result() is replaced with ->fetchField(); Db_query (“adb=%d,%s”, $a, $b) is replaced with Db_query(“abd=:a,:b”, array(‘:a’=>$a, ‘:b’=>$b));

Más contenido relacionado

La actualidad más candente

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
references
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
iKlaus
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
AidIQ
 

La actualidad más candente (20)

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Keeping It Simple
Keeping It SimpleKeeping It Simple
Keeping It Simple
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Theme API
Theme APITheme API
Theme API
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
$.Template
$.Template$.Template
$.Template
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Daily notes
Daily notesDaily notes
Daily notes
 

Similar a Views notwithstanding

Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
DrupalCampDN
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
Naoya Ito
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 
Building a horizontally scalable API in php
Building a horizontally scalable API in phpBuilding a horizontally scalable API in php
Building a horizontally scalable API in php
Wade Womersley
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 

Similar a Views notwithstanding (20)

Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
 
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarSugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
 
Jquery
JqueryJquery
Jquery
 
Framework
FrameworkFramework
Framework
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
 
Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)
 
Ubi comp27nov04
Ubi comp27nov04Ubi comp27nov04
Ubi comp27nov04
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Building a horizontally scalable API in php
Building a horizontally scalable API in phpBuilding a horizontally scalable API in php
Building a horizontally scalable API in php
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Views notwithstanding

  • 1. Views Notwithstanding A Programmer’s guide to working with MySQL Tables in Drupal using PHP and SQL -- Srikanth Bangalore. Bangalore.srikanth@gmail.com Drupal ID: bangalos
  • 2. Drupal APIs (in PHP) for: Creating a table During installation of your custom module Post installation of your custom module Inserting into table Querying the table and iterating over rows Creating a “Block” Creating an Admin “menu” (form) Creating a form
  • 3. Creating a Table (during installation of custom module) hotornot.info name = Hot Or Not description = Builds A Hot Or Not Block, And Lets Users Rate Images In A Folder. package = Hot Or Not core = 6.x hotornot.module (to be populated later) hotornot.install (see next slide)
  • 4. Hotornot.install <?php function hotornot_install() { switch ($GLOBALS['db_type']) { case 'mysql': case 'mysqli': // the {tablename} syntax is so multisite installs can add a prefix to the table name as set in the settings.php file db_query("CREATE TABLE {hotornot_filelist} ( file_idint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, file_pathvarchar(256) NOT NULL DEFAULT './.', present_or_notsmallint unsigned NOT NULL DEFAULT 1, title varchar(256), description text ) /*!40100 DEFAULT CHARACTER SET utf8 */;"); break; } }
  • 5. Adding Another Table later function hotornot_update_1() { switch ($GLOBALS['db_type']) { case 'mysql': case 'mysqli': db_query ("CREATE TABLE {hotornot_userchoice} ( file_idint unsigned NOT NULL DEFAULT 0, uidint unsigned NOT NULL DEFAULT 0, hot_or_notsmallint unsigned NOT NULL DEFAULT 0, PRIMARY KEY (file_id, uid) ) /*!40100 DEFAULT CHARACTER SET utf8 */;"); break; } }
  • 6. Things To Remember … db_query function accepts an SQL statement as input, and executes it.
  • 7. function hotornot_repopulate() { $path_to_files = realpath('.') . variable_get('hotornot_folder', '/sites/default/files/hotornot'); $output = ""; $isql = "UPDATE {hotornot_filelist} SET present_or_not = 0 WHERE file_id>0"; $iresult = db_query($isql); if ($handle = opendir($path_to_files)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $output .= "$file"; $query = "SELECT COUNT(*) FROM {hotornot_filelist} WHERE file_path = '$file'"; $num = db_result(db_query($query)); if($num) { $isql = "UPDATE {hotornot_filelist} SET present_or_not=1 WHERE file_path = '$file'"; $iresult = db_query($isql, $file); } else { $isql = "INSERT INTO {hotornot_filelist} (file_path, present_or_not) VALUES ('%s', 1)"; $iresult = db_query($isql, $file); } } } closedir($handle); } drupal_set_message($output); }
  • 8. Things To Remember … db_query function accepts an SQL statement as input, and executes it. db_result(db_query($sql)) extracts the SINGLE value of the db_query result. variable_get function is used to get the value of a programmer-defined variable. (see later).
  • 9. hotornot.module – part 1: adding the admin menu (a) <?php function hotornot_menu() { $items = array(); $items['admin/settings/hotornot'] = array( 'title' => t('Hot Or Not'), 'description' => t('Select The Hot Or Not Image Folder'), 'page callback' => 'drupal_get_form', 'page arguments' => array('hotornot_admin_settings'), 'access arguments' => array('administer site configuration'), ); return $items; } ….(see next slide)
  • 10. hotornot.module – part 1: adding the admin menu (b) function hotornot_admin_settings() { $form = array(); $form['hotornot_folder'] = array( '#type' => 'textfield', '#title' => t('The folder where all the images for the Hot Or Not are Stored'), '#default_value' => variable_get('hotornot_folder', 'sites/default/files/hotornot'), ); $form['hotornot_repopulate'] = array( '#type' => 'submit', '#value' => 'Repopulate', ); $form['#submit'][] = 'hotornot_admin_settings_submit_handler'; return system_settings_form($form); } function hotornot_admin_settings_submit_handler(&$form, &$form_state) { if ($form_state['clicked_button']['#id'] == 'edit-hotornot-repopulate') { hotornot_repopulate(); } }
  • 11. Things to remember … Use drupal forms api to build the forms, even the Admin forms. 3 steps to having your own module’s admin settings form: Define path + form_builder_function in hook_menu(); Build your form using the forms API. Remember to wrap your form with “system_settings_form” Do your “stuff” in the submit handler.
  • 12. hotornot.module – part 2adding the block (a) function hotornot_block($op = 'list', $delta = 0, $edit = array()) { switch ($op) { case 'list': $blocks[0]['info'] = t('Rate this!'); return $blocks; case 'view': if ($delta == 0 ) { $block[0]['subject'] = t("Do you like ..."); $block[0]['content'] = drupal_get_form('hotornot_hotornotform'); } return $block[$delta]; } }
  • 13. hotornot.module – part 2adding the block (b) function hotornot_hotornotform(&$form_state) { $form = array(); global $user; $sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS file_title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND (filelist.file_id not in (SELECT file_id FROM {hotornot_userchoice} WHERE uid=%d)) ORDER BY RAND() LIMIT 1"; $result = db_query($sql, $user->uid); $atleastoneexists = FALSE; while ($row = db_fetch_array($result)) { $atleastoneexists = TRUE; $form['my_fileid'] = array( '#type' => 'hidden', '#value' => $row['file_id'] );
  • 14. hotornot.module – part 2adding the block (c) $form['picture'] = array( '#type' => 'markup', '#value' => '<img width="100%" src="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/><br/><strong>...'. $row['file_title'] . ' ?</strong><br/>', ); break; } if ($atleastoneexists) { $form['ishot'] = array( '#type' => 'submit', '#value' => t('Yes') ); $form['isnot'] = array( '#type' => 'submit', '#value' => t('No') ); } else { $form['picture'] = array( '#type' => 'markup', '#value' => '<p>Currently, you have seen all the items. Thank you.</p>', ); } return $form; }
  • 15. hotornot.module – part 2adding the block (d) function hotornot_hotornotform_submit(&$form, &$form_state) { global $user; if ($form_state['clicked_button']['#id'] == 'edit-ishot') { $ishot = 1; } else { $ishot = 0; } $fileid = $form_state['clicked_button']['#post']['my_fileid']; $isql = "REPLACE INTO {hotornot_userchoice} (file_id, uid, hot_or_not) VALUES (%d, %d, %d)"; $iresult = db_query($isql, $fileid, $user->uid, $ishot); }
  • 16. Things To Remember … db_query function accepts an SQL statement as input, and executes it. db_result(db_query($sql)) extracts the SINGLE value of the db_query result. To get the rows of the query result in an iterator. $result = db_query($sql); while ($row = db_fetch_array($result)) { $val = $row[‘column_name’] }
  • 17. hotornot.module – part 3adding a page to enter title/desc (a) function hotornot_menu() { $items = array(); // ...code... $items['hotornot/administer'] = array( 'title' => t('Hot Or Not Administration'), 'description' => t('Add Or Edit Title And Descriptions to Hot Or Not Items'), 'page callback' => 'local_hotornot_administer_description_form', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); // ...code... return $items; } function local_hotornot_administer_description_form() { return drupal_get_form('hotornot_administer_description_form'); }
  • 18. hotornot.module – part 3adding a page to enter title/desc (b) function hotornot_administer_description_form(&$form_state) { $form = array(); global $user; $form['blurb'] = array ( '#type' => 'markup', '#value' => '<p>You will be shown one picture at a time that does not have any title or description. You just have to enter a title and description and hit submit.</p>' , ); $sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND filelist.title is NULL LIMIT 1"; $result = db_query($sql); $atleastoneexists = FALSE; while ($row = db_fetch_array($result)) {
  • 19. hotornot.module – part 3adding a page to enter title/desc (c) $atleastoneexists = TRUE; $form['fileid'] = array( '#type' => 'hidden', '#value' => $row['file_id'] ); $form['picture'] = array( '#type' => 'markup', '#value' => '<imgsrc="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/>', ); $form['title'] = array( '#type' => 'textfield', '#title' => 'Title', '#default_value' => $row['title'], ); } if ($atleastoneexists) { $form['submit'] = array( '#type' => 'submit', '#value' => 'Submit', );
  • 20. hotornot.module – part 3adding a page to enter title/desc (d) } else { $form['picture'] = array( '#type' => 'markup', '#value' => '<p>Currently, you have seen all the items. Thank you.</p>', ); } return $form; } function hotornot_administer_description_form_submit(&$form, &$form_state) { $fileid = $form_state['values']['fileid']; $title = $form_state['values']['title']; $isql = "UPDATE {hotornot_filelist} SET title='%s' WHERE file_id=%d"; $iresult = db_query($isql, $title, $fileid); }
  • 21. Summary We learnt how to create a new table at the time of installing our module How to use db_query, db_result, db_fetch_array How to create user blocks and user pages How to create Admin menus and define new variables How to use Forms API
  • 22. Drupal 7 changes Switch(db_type) does not work! Db_result() is replaced with ->fetchField(); Db_query (“adb=%d,%s”, $a, $b) is replaced with Db_query(“abd=:a,:b”, array(‘:a’=>$a, ‘:b’=>$b));