Sunteți pe pagina 1din 12

Note: Modify several code suitable D7 Link : http://www.semicolon.co.za/mysql_tutorials/create-hello-world-module-drupal6-part2.

html

Hello World module in Drupal 6 Part 1


A short tutorial on developing a simple hello world module that prints Hello World on the screen. 1. Create a folder for your module Create a folder in your modules directory called helloworld ie sites/all/modules/helloworld/. It is good practice to put all custom modules in sites/all/modules/ folder and not the modules/ folder. The modulesfolder is meant for core modules any third party or custom modules should be in sites/all/modules/. So now that youve created the folder sites/all/modules/helloworld/ 2. Create the *.info file Create a file called modulename.info in this case helloworld.info 1 ; $Id$ 2 name = Hello World Module 3 description = My very first Drupal Module 4 core = 6.x This lets Drupal know about your module 3. Create the *.module file Create a file called modulename.module in this case helloworld.module We need to let Drupal know what path the module will be accessible from. We do this by using thehook_menu() hook. To implement hooks follow the following convention: modulename_hookname(). So for our module we must create a function called helloworld_menu(). More info here. 1 function helloworld_menu(){ 2 $items = array(); 3 $items['helloworld'] = array(

4 'title' => t('Welcome to the Hello World Module'), 5 'page callback' => 'helloworld_page', 6 'page arguments' => array(1), 7 'access arguments' => array('access content'), 8 'type' => MENU_CALLBACK, 9 ); 10 return $items; 11 } Break Down We created $items['helloworld'] array item. This lets drupal know about the path we want to use for our module. title: this is what gets printed at the top of the page. The page title. page callback: This is the function that gets called when the url is accesed. page arguments: must be array of arguments that get parsed to the call back function, not required. access arguments: array of access permissions in this case any role with access content permissions can access the page. type: specifies the menu type check hook_menu() for more details the Drupal hook. There are more available options than these. The Drupal API is your friend. Use it. So in a nutshell, when Drupal hits the http://mysite.com/helloworld url it will look for a call back function called helloworld_page(). Simple Enough. Now lets create the helloworld_page() function. 1 function helloworld_page($argument) { 2 return "Hello World!"; 3} So your helloworld.module file will contain: 1 <?php 2 function helloworld_menu(){ 3 $items = array(); 4 $items['helloworld'] = array( 5 'title' => t('Welcome to the Hello World Module'),

6 'page callback' => 'helloworld_page', 7 'page arguments' => array(1), 8 'access arguments' => array('access content'), 9 'type' => MENU_CALLBACK, 10 ); 11 return $items; 12 } 13 function helloworld_page($argument) { 14 return "Hello World! Arguments parsed was " . $argument; 15 } Note how i did not close the <?php tag. It is considered good practice to no close files that only contain php. Now go to admin>build>modules. Your module should be on the list. Activate it and type in http://mysite.com/helloworld to test it out. Goodluck Ill doing a secong part to this tutorial where i will show you how to create an input form and save user the input to the database. You can download the complete drupal module.

Hello World module in Drupal 6 Tutorial Part 2


Hey all, welcome to part 2, a continuation of the Hello World module in Drupal 6 Part 1 I know what youre thinking: A full 8 months later? wtf?. If you werent thinking that then you are now. Or something along those lines. I apologise for the delay(if you can even call it that). Blah blah blah 1 {begin: excuse} 2 //TODO: enter excuses here 3 {end: excuse} Now that weve got that out of the way, Shall we then get to the Semicontacts Module tutorial. Right. In this tutorial we are going to learn the following

1. How to use the Drupal Database Abstraction Layer. 2. How to use the Drupal Form API to create and validate forms. 3. How to use the Drupal Schema API to create a database table during module installation. 1 NOTE: Please note that this tutorial is used for educational purposes only.<br /> 2 It is nowhere near production ready. Also what we are doing here can be done<br /> 3 without any coding at all using the <a href="http://drupal.org/project/cck">CCK module</a>. This is just meant to show you actual Drupal Code

Our module is an address book much like the one you have on your phone. It will require a first name, last name, phone number. These will then be saved in a database in a table called semicontacts that we will create. We will also create a page to list all these contacts. Okay less yada yada more code you say? Say no more. So were going to create module folder and the two required files like in part one. So now I have a folder in sites/all/modules/ called semicontacts(the name of my module): -sites/all/modules/semicontacts semicontacts.info semicontacts.module Lets start by telling Drupal about our module in the semicontacts.info file: 1 ; $Id$ 2 name = Semicolon Contacts Module description = Contact Management Module(CMM <img src="http://www.semicolon.co.za/wpincludes/images/smilies/icon_biggrin.gif" alt=":D" class="wp-smiley"> ) 4 core = 6.x 3 5 package = Semicolon Now Drupal knows about our module. If you actually go into modules list you will see this new module.

Now lets edit the semicontacts.module file and add a page(tell Drupal the URL for the module), you will remember we do this by using a hook_menu() hook. If you remember in part 1, hooks naming follows nameofmodule_hookname() what does this mean for us?: 1 <?php 2 function semicontacts_menu(){ 3 $items = array(); 4 $items['semicontacts'] = array( 5 'title' => t('Semicontacts - Form'), 6 'page callback' => 'semicontacts_page', 7 'access arguments' => array('access content'), 8 'type' => MENU_CALLBACK, 9 ); 10 return $items; 11 } As you can see the module will be accessible from the http://mysite.com/semicontacts page. The page call-back is the function that will be called when this URL is accessed. So lets go ahead and create that. This page will contain our form. We will use the Form API to create the form. 1 function semicontacts_page($argument) { 2 $content = "Hello World! Wow It really works 3 4 5 6 7} Theres our function. So we put a little into text at the top and we add a form to that using thedrupal_get_form() function, which takes a form function as a parameter. So we need to create this form function that will return our form. 1 function semicontacts_form(){ 2 $form = array(); 3 //create a text field called firstname with label First Name 4 $form['firstname'] = array( This is a simple module to save contacts to the database. Enter Contact Details."; $content .= drupal_get_form('semicontacts_form'); return $content;

5 '#type' => 'textfield', 6 '#title' => t('First Nmae'), 7 ); 8 //create a text field called lastname with label Last Name 9 $form['lastname'] = array( 10 '#type' => 'textfield', 11 '#title' => t('Last Name'), 12 ); 13 //create a text field called phonenumber with label Phone Number 14 $form['phonenumber'] = array( 15 '#type' => 'textfield', 16 '#title' => t('Phone Number'), 17 ); 18 //create submit button 19 $form['submit'] = array( 20 '#type' => 'submit', 21 '#value' => t('Save Contact'), 22 ); 23 //return the form 24 return $form; 25 } The Form API makes creating our form simpler and cleaner. The form is declared as an array of arrays(the fields are themselves arrays). By the ways this function can be called whatever you want. As long you fetch the right form in the page function above. So now we should have a form. Lets try access the page. Go to http://www.my-site.com/semicontacts You should be greeted with a form which at the moment does absolutely nothing. Try click submit. It should just redirect you to the same page. Okay. Now lets get to the fun stuff. Lets create a table in our database called semiccontacts to store our contacts: 1 CREATE TABLE `semicontacts`.`helloworld_contacts` ( 2 `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , 3 `firstname` VARCHAR( 255 ) NOT NULL ,

4 `lastname` VARCHAR( 255 ) NOT NULL , 5 `phonenumber` VARCHAR( 255 ) NOT NULL 6) Copy sql query above and run in a mysql client(i use phpMyAdmin). Be sure you have already selected your drupal database. Now we just need to create a function to save our form. We do this by implementing form apis _submit() function 1 function semicontacts_form_submit($form_id, &$form_data){ db_query("INSERT INTO semicontacts (firstname, lastname, phonenumber) VALUES ('%s', '%s', 2 '%s')", $form_data['values']['firstname'],$form_data['values']['lastname'], $form_data['values'] ['phonenumber']); 3 drupal_set_message(t('Your contact has been saved to the database.')); 4} The data submitted by the form is stored in an array $form_data['values'] with field names as keys so to fetch the value of firstname field just $form_data['values']['firstname'], simple enough right? Yep. In Drupal 7, We use the db_insert to save our data. The API allows for method chaining, much likeRUBYs active record pattern or Jqeury. Looks better and makes the code easier to follow. So to save this in drupal 7 we would use: 1 db_insert('semicontacts')->fields($form_data)->execute(); So now our form should be saving to the database. Try it now. Works? Yes? No? If it doesnt then something went wrong up there. You or i(i hope not) missed something. Wait dont we need to validate our form data? We do. Lets. Form validation is done using the form api _validate() function. It means our function will be called semicontacts_validate(). 1 function semicontacts_form_validate($form_id, &$form_data){ 2 //var_dump($form_value); 3 if(!is_string($form_data['values']['firstname'])||empty($form_data['values']['firstname'])){ 4 form_set_error('firstname', t("Please Enter a valid First Name")); 5 }elseif(!is_string($form_data['values']['lastname'])

||empty($form_data['values']['lastname'])){ 6 form_set_error('lastname', t("Please Enter a valid Last Name")); }elseif(!is_numeric($form_data['values']['phonenumber']) ||empty($form_data['values']['phonenumber'])){ 8 form_set_error('phonenumber', t("Please Enter a valid Phone Number")); 7 9 } 10 } We used the the form_set_error function to set errors if any for the field we are currently validating. the method takes a fieldname and an error message. You will also notice like the submit function we did not have to call them. This is the beauty of hooks. Theyre like that little kid in class with his hand up going me,me,me, pick me sir. And the class wont continue until they get picked. I thought that was deep. You should write that down So hooks break drupal flow of execution cause drupal will first check if there are any relevant hooks in your module before continuing to the next task. So its almost like you modified the Drupal core without really needing to see the core code. Okay now try submitting without entering any values. You should get the error messages we defined above. But wait wouldnt it be cool if we had a page to list contacts? Lets go ahead and do that. Remeber that secontacts_menu function up there, the one that defines our modules urls? Yeah that one. Lets add another url there. Say http://www.my-site.com/semicontacts/list 1 function semicontacts_menu(){ 2 $items = array(); 3 $items['semicontacts'] = array( 4 'title' => t('Semicontacts - Form'), 5 'page callback' => 'semicontacts_page', 6 'access arguments' => array('access content'), 7 'type' => MENU_CALLBACK,

8 ); 9 $items['semicontacts/list'] = array( 10 'title' => t('Semicontacts - List'), 11 'page callback' => 'semicontacts_list_page', 12 'page arguments' => array("1"), 13 'access arguments' => array('access content'), 14 'type' => MENU_CALLBACK, 15 ); 16 return $items; 17 } Easy enough. If at this point you are thinking we need to create the call back function you are indeed correct young grasshoper Here it is:

1 function semicontacts_list_page($argument) { 2 $content = t("List of contacts<br /><br />"); 3 $content .= t(l("Add New Contact","semicontacts")); 4 $result = db_query('SELECT c.id, c.firstname, c.lastname, c.phonenumber FROM semicontacts c order by

5 lastname asc'); 6 $content .= "<ul>"; 7 while ($contact = db_fetch_object($result)) { 8 $content .= "<li>$contact->lastname, $contact->firstname - $contact>phonenumber</li>";// Perform

9 operations on $node->body, etc. here. 10 } 11 $content .= "</ul>"; 12 $content .= l(t("Add New Contact"),"semicontacts"); 13 return $content; 14 } At this point our module is fully functional. But we dont want the end-user to always run a sql command to create the semicontacts table. We need this to happen during module installation. Enter the semicontacts.install module with the Schema API Create a new file in the semicontacts folder called semicontacts.install with the following contents: 1 <?ph

p //$I 2 d 3 /** 4 * Implement hook_schema() 5 */ 6 function semicontacts_schema(){ 7 $schema['semicontacts'] = array( 8 'description' => t('Store .'), 9 'fields'=>array( 10 'id'=>array( 11 'type'=>'serial', 12 'unsigned'=>TRUE, 13 'not null'=>TRUE 14 ), 15 'firstname'=>array( 16 'type'=>'varchar', 17 'length'=>255, 18 'default' => '', 19 'not null'=>TRUE 20 ), 21 'lastname'=>array( 22 'type'=>'varchar', 23 'length'=>255, 24 'default' => '', 25 'not null'=>TRUE 26 ), 27 'phonenumber'=>array( 28 'type'=>'varchar', 29 'length'=>255, 30 'default' => '', 31 'not null'=>TRUE 32 ), 33 ), 34 'primary key'=>array("id"), 35 ); 36 return $schema; 37 } 38 /**

39 * Implement hook_install() 40 */ 41 function semicontacts_install(){ 42 drupal_install_schema('semicontacts'); 43 } 44 /** 45 * Implement hook_uninstall 46 */ 47 function semicontacts_uninstall(){ 48 drupal_uninstall_schema('semicontacts'); 49 } This file contains implementation of 3 drupal hooks, hook_install(), hook_uninstall(), hook_schema(). hook_install() is used to run any configuration during install like say creating a database table for our module. hook_uninstall() is used to run any configuration during install like say deleting a database table for our module. hook_schema() is where we define our database table. The fields about are clearly self explanatory. Check a full list and description. To test your new install file you must remove the module from Drupal system table. This makes sure that Drupal will run hook_install() since this only runs the first time a module is installed. To do that I usually just run this query 1 delete from system where name ="semicontacts" Not the best way, not even advisable. to execute queries directly on the database, but it should suffice since we are on our localhost. So now you need to package your module in to a .tar.gz file. If you are on windows download 7zip. To create the file just right click on the semicontacts folder, go to the 7zip submenu and click on add to

archive, on the window that pops up,choose tar format. you should have a newfile semicontacts.tar. Right click this file and do the same as above but choose gzip as the archive format. Good luck. Comments welcome positive and negative. I apologise for the lenghth of the tutorial, was just so much stuff to cover. We are going to improve and extend semicontacts in the next tutorial(Part 3)

S-ar putea să vă placă și