How to create a custom form in drupal

May 05, 2012


This is a series of drupals amazing tutorial (3 parts).

Part One is a step by step tutorials on how to create custom module in drupal in amazing way
Part two depends on first part. It uses first part module. This part describes how to create custom form in drupal in simplest and most easiest way
Third part depends on second part. This part describes how to create drupal table in correct, perfect and most descriptive way

Making custom form in drupal is so easy. Just follow the simple 3/4 steps, you will be master in drupal form.It is very much essential for a drupal developer, how to create a perfect drupal form.

you need to know

Before creating drupal form, you need to learn how to create drupal module. Please read How to create drupal 6 custom module in three esay steps before going further.

Final Output

After complete this tutorials you will see drupal generated from

Rebuild callback function

Code of our previous callback function was:

<?php /** * callback function for person */ function person_personal_info(){ $output 'Name: Hasan Hafiz<br />
$output .= 'City: Dhaka<br />
$output .= 'Country: Bangladesh<br />
; return $output; } ?>

Erase code after opening brace { and before ending } brace and write : <?php /** * menu callback; person add form */ function person_personal_info(){ // drupal_get_form($form_id) // $form_id: The unique string identifying the desired form $output = drupal_get_form('person_add_form'); return $output; } ?>

Here, 'person_add_form' is the form id. Later we have to create a function similiar to form id to crate drupal from.


Functions to know before creating form

Before going further, lets familiar with some drupal function and their purpose

  • drupal_get_form() = Generates drupal form. Visit Drupal API site for more information.
  • form_set_error() = Display error generate by form element. Visit Drupal API site for more information.
  • drupal_set_message() = To Display any type of message like error, warning or ok. Visit Drupal API site for more information.
  • drupal_set_title() = Setting page title for current page. Visit Drupal API site for more information.

Drupal Form API properties to create form element

Some form properties are common and some properties are optional and some are default.

But at least two properties title and type are needed to crate any form element.

Remember carefully, do not forget to add hash sign '#' before form properties.

Create from element

Create a function similiar to form id as i mentioned above and define form element

<?php/** * form builder; person add form */ function person_add_form($form_state){ // drupal_set_title('Add New Person'); $form = array(); $form['name'] = array( '#title' =&gt; 'Your Name', '#type' =&gt; 'textfield', '#size' =&gt; '30', ); $form['city'] = array( '#title' =&gt; 'Your City', '#type' =&gt; 'textfield', '#size' =&gt; '30', ); $form['country'] = array( '#title' =&gt; 'Your Country', '#type' =&gt; 'textfield', '#size' =&gt; '30', ); $form['submit'] = array( '#type' =&gt; 'submit', '#value' =&gt; 'Submit', ); return $form; } ?>

Newly created drupal form will be shown after visiting person link

Visit Drupal Api site for list of Form API properties and their uses

Changing default page title

Normally, Menu title acts as a page title. To change it use drupal_set_title() function. Write below code just after the form builder function person_add_form(). Now refresh your page, new page title will be show

<?phpdrupal_set_title('Add New Person'); ?>

Form Validation

To validate a form, drupal looks for built in function formid_validate. Since our form id is : person_add_form so, our validate functions name will be; person_add_form_validate.

Lets create a validate function and display a message to see our validate function works or not

<?php/** * validate function for person add form * *@param $form An associative array containing the structure of the form *@param $form_state A keyed array containing the current state of the form */ function person_add_form_validate($form,$form_state){ // display a sample message that, our form is submitted drupal_set_message('validate function called successfully.'); } ?>

Now after clicking submit button you will see a message validate function called successfully. See bellow firgure

Further Form Validation: person name validation

Lets create a helper function pretty_print() to see form submitted value

<?php// helper function to display form data function pretty_print($data=''){ drupal_set_message('?>

<?php' . print_r($data,true) . '?>

<?php'); } ?>

Add the newly created pretty_print() to person_add_form_validate()

<?php/** * validate function for person add form * * @param $form An associative array containing the structure of the form * @param $form_state A keyed array containing the current state of the form */ function person_add_form_validate($form,$form_state){ // display a sample message that, our form is submitted drupal_set_message('validate function called successfully.'); pretty_print($form_state); // to display form submitted data } ?>

Now fillup your form field with some values and click submit button, you will see an associative array containing the current state of the form as like below figure

Working with form submitted value

The current user-submitted data is stored in $form_state['values']. So to get a person name you have to write:

<?php$name $form_state['values']['name']; ?>

Now, validate a person name with the following condition.

  • It could not be blank or empty
  • It must be greater than or equal to 6 characters

If above condition fails, generate an error. So our final form validation function code looks like

<?php/** * validate function for person add form * * @param $form An associative array containing the structure of the form * @param $form_state A keyed array containing the current state of the form */ function person_add_form_validate($form,$form_state){ // display a sample message that, our form is submitted // drupal_set_message('validate function called successfully.'); // pretty_print($form_state); $name = $form_state['values']['name']; if (trim($name) == '' || strlen(trim($name)) &lt; 6 ){ form_set_error('name','Person Name is either empty or Less than 6 characters.'); } } ?>

Now if your name is empty or blank or less than 6 character , you will get an error message after submitting form (see below figure)

Store person data to database

Creating person table

open phpmyadmin, select drupal database. Now select SQL tab and paste the sql code. Finally click go button to run code


Create submit function

After submitting a form, drupal looks for built in function formid_submit. Since our form id is : person_add_form so, our submit function name will be; person_add_form_submit.

Lets create a submit function and insert data to person table

<?php/** * submit function for person add form * * @param $form An associative array containing the structure of the form * @param $form_state A keyed array containing the current state of the form */ function person_add_form_submit($form,$form_state){ $name trim($form_state['values']['name']); $city trim($form_state['values']['city']); $country trim($form_state['values']['country']); $query "INSERT INTO person (`name`,city,country) VALUES ('%s', '%s', '%s')"$result db_query($query$name$city$country); if ($result !== FALSE){ drupal_set_message('data saved successfully.'); } } ?>

For a complete list of drupal database relation functions, visit Drupal database API and for common database functions visit Drupal's Common database API functions.