You are on page 1of 12

Web applications today are being used in all kinds of industries.

They need to take in and process a lot of user


data. The capturing of the data happens through HTML forms which let you create different types of input elds
like textboxes, radio buttons etc. using HTML tags. These forms get difcult to maintain or update if they are
written directly in the HTML code. Drupal provides a very good way of dening forms directly in your PHP code,
while the form generation is done by Drupal itself. This makes it easy for you to create and maintain forms. In
this article we are going to see how we can create forms in Drupal. The nal code can be cloned fromGithub.

The drupal_get_form function Form generation in


Drupal
The whole magic of form creation in Drupal is performed by the functiondrupal_get_form. This function
returns a renderable form array to the Drupal system. It takes an argument as the form_id: a unique identier to
identify the form, and if a function with the same name exits then that function is called to build it. You can read
more aboutdrupal_get_format the
linkhttps://api.drupal.org/api/drupal/includes!form.inc/function/drupal_get_form/7

Creating a basic form in Drupal


Lets start by creating a small module which will create a menu callback and then on that menu callback create a
form using thedrupal_get_formfunction. To create a module add a folder to your Drupal
installationsites\all\modules\drupalformand add two les to
it:drupalform.infoanddrupalform.modulewith the following code:
drupalform.info
name=drupalform
description=ThismodulecreatesaformusingDrupal.
core=7.x

drupalform.module
<?php
/**
*@file

*Thisisthemainmodulefile.
*/
/**
*Implementshook_help().
*/
functiondrupalform_help($path,$arg){

if($path=='admin/help#rupalform'){
$output='<h3>'.t('About').'</h3>';
$output.='<p>'.t('Thedrupalformmoduleshowshowtocreateformsusin
return$output;
}
}

With the above code you should be able to see your module in the available module list and should be able to
enable it as shown below. If these steps seem mysterious or complicated, please see my last tutorial for a
goodDrupal Module introduction.

Once we have done this we will add a menu callback usinghook_menuand create a form on the page. The code
for that is as follows

/**
*Implementationofhook_menu().
*/
functiondrupalform_menu(){
$items['drupalform/form1']=array(
'type'=>MENU_CALLBACK,
'accessarguments'=>array('accesscontent'),
'pagecallback'=>'drupal_get_form',
'pagearguments'=>array('drupalform_form1'));

return$items;
}
functiondrupalform_form1(){
$form=array();

$form['name']=array(
'#type'=>'textfield',
'#title'=>t('Enteryourname'),
'#description'=>t('Yourfirstnamegoeshere')
);
$form['last_name']=array(
'#type'=>'textfield',
'#title'=>t('EnteryourLastname'),
'#description'=>t('YourLastnamegoeshere')
);
$form['email']=array(
'#type'=>'textfield',
'#title'=>t('Enteryouremail'),
'#description'=>t('Youremailgoeshere')
);
$form['country']=array(
'#type'=>'select',
'#title'=>t('Selectyourcountry'),
'#options'=>array('USA','UK','France','Japan')
);
$form['submit']=array(
'#type'=>'submit',
'#value'=>t('Submit')
);
return$form;
}

In the above code in the implementation ofhook_menuwe create a menu item


whosepage_callbackisdrupal_get_formand the argument to that is

theform_id"drupalform_form1". The functiondrupalform_form1returns the form array which we want to


create.
In the functiondrupalform_form1we create three text elds: name, last_name, email, and one select box
for the country. In the select box we specify the options of the country with an array. We have also added a
Submit button, so the user can actually submit the form. Now you should be able to go to your menu url:<your
drupalbaseurl>/drupalform/form1and see the form as follows

Validating a Drupal form


Drupal uses naming conventions heavily to identify which functions to call on which events. The complete
Drupal hook system is based on naming conventions. Similarly, the function called to validate your form data
has to follow the naming convention<form_id>_validateand it will be passed theform_stateas a
variable.
Hence, for our form the function name will be:
drupalform_form1_validate($form,$form_state).
The values which the user has entered will be present in an array$form_state['values']with the same id

functiondrupalform_form1_validate($form,$form_state){
if(empty($form_state['values']['name']))
form_set_error('name','Namecannotbeempty');
elseif(empty($form_state['values']['last_name']))

form_set_error('last_name','Lastnamecannotbeempty');
elseif(filter_var($form_state['values']['email'],FILTER_VALIDATE_EMAIL)==
form_set_error('email','Emailisnotvalid');
}

In the above function we check if the name and last_name are not empty and that the email is valid. If that is not
the case we set a form error using the Drupal functionform_set_error. This will display the error to the
user and the form will not be submitted.
If you submit the form by entering an empty name you should see the following error on the screen:

Submitting a Drupal form


Similar to the validation function the submit function is also called based on the naming convention and the
function name should be<form_id>_submit. Again, the variable$form_statewill be passed to it. Our
submit function will thus be dened as:

//Dependingonthetypeofformyoucanaddthelogic
//tostorethedetailsoftheform
//byaddingitinaDrupaltable.
//orsendingamailtotheadmin
//Storinginafile
//orpassittosomeotherservice
drupal_set_message("Formhasbeensubmitted");
}

Now if we pass all the valid elds you will get the following message on screen.

Using Field sets in Drupal Forms to separate elements.


Sometimes when the form is bigger and has many elds you might want to break it into small sections so that
the form seems more logical to the user. To do this you can create eldsets in Drupal to create groups of elds.
To create a eldset calledbasicdetailsto hold the elds we dened above we will have to update
thedrupalform_form1as follows

functiondrupalform_form1(){
$form=array();

$form['basicdetails']=array(
'#type'=>'fieldset',
'#title'=>t('EnteryourBasicdetailsbelow'),
'#description'=>t('Theseareallmadatory')
);

$form['basicdetails']['name']=array(
'#type'=>'textfield',
'#title'=>t('Enteryourname'),
'#description'=>t('Yourfirstnamegoeshere')
);
$form['basicdetails']['last_name']=array(
'#type'=>'textfield',
'#title'=>t('EnteryourLastname'),
'#description'=>t('YourLastnamegoeshere')
);
$form['basicdetails']['email']=array(
'#type'=>'textfield',
'#title'=>t('Enteryouremail'),
'#description'=>t('Youremailgoeshere')
);

$form['submit']=array(
'#type'=>'submit',
'#value'=>t('Submit')
);
return$form;
}

This will create a separate eldset as shown below

The different form elements that can be used in Drupal


forms
Drupal provides a great number of different types of elds which we can use in our forms. I will update our form
to use some of these by creating two more eld sets for address details and additional details.
The updated code is below:

functiondrupalform_form1(){
$form=array();

$form['basicdetails']=array(
'#type'=>'fieldset',
'#title'=>t('EnteryourBasicdetailsbelow'),
'#description'=>t('Theseareallmadatory')
);
$form['basicdetails']['name']=array(
'#type'=>'textfield',

'#title'=>t('Enteryourname'),
'#description'=>t('Yourfirstnamegoeshere')
);
$form['basicdetails']['last_name']=array(
'#type'=>'textfield',
'#title'=>t('EnteryourLastname'),
'#description'=>t('YourLastnamegoeshere')
);
$form['basicdetails']['email']=array(
'#type'=>'textfield',
'#title'=>t('Enteryouremail'),
'#description'=>t('Youremailgoeshere')
);
$form['addressdetails']=array(
'#type'=>'fieldset',
'#title'=>t('EnteryourAddressdetailsbelow'),
'#description'=>t('Theseareallmadatory')
);
$form['addressdetails']['country']=array(
'#type'=>'select',
'#title'=>t('Selectyourcountry'),
'#options'=>array('USA','UK','France','Japan')
);
$form['addressdetails']['city']=array(
'#type'=>'textfield',
'#title'=>t('Enteryourcity'),
'#description'=>t('Yourcitynamegoeshere')
);
$form['addressdetails']['localaddress']=array(
'#type'=>'textarea',
'#title'=>t('Enteraddress'),
'#description'=>t('YourAddressnamegoeshere')
);
$form['additionaldetails']=array(
'#type'=>'fieldset',
'#title'=>t('Enteryourotherdetailsbelow'),
'#description'=>t('Thesearealloptional')

$form['additionaldetails']['gender']=array(
'#type'=>'radios',
'#title'=>t('Gender'),
'#options'=>array('Male','Female')
);
$form['additionaldetails']['suscribtion']=array(
'#type'=>'checkboxes',
'#title'=>t('Iwanttosubscribefor'),
'#options'=>array('Emailnewsletter','Offervouchers')
);
$form['additionaldetails']['birthdate']=array(
'#type'=>'date',
'#title'=>t('Birthdate'),
);
$form['#attributes']['enctype']='multipart/formdata';
$form['additionaldetails']['picture']=array(
'#type'=>'file',
'#title'=>t('Uploadyourpicture'),
);

$form['submit']=array(
'#type'=>'submit',
'#value'=>t('Submit')
);
return$form;
}

This is what the new eldsets look like:

Conclusion
Drupal helps you create and process forms right inside your module. The APIs Drupal offers make it very simple
to make an addition or modication of your form as the forms are arrays and even the validation and submission
happens in a different function. This modular approach keeps the form code in your module clean and easy to
maintain. You also do not need to bother with the HTML details of the form if you use the Drupal form API all
the HTML is auto-generated. Have fun creating your next form in your Drupal module!
If you'd like us to cover a more specic use case or go into more details, or just have feedback, let us know in the

You might also like