Webemania | How to create a custom form in drupal

| Published Date: 30 May 2012 | Last Updated Date: 04 Sep 2017
Total Reads: 56,154 | Last Visit: 22 Sep 2017 06:32:26 AM
Note

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:

  1. /**
  2.  * callback function for person
  3.  */
  4. function person_personal_info(){
  5. $output = 'Name: Hasan Hafiz </br>';
  6. $output .= 'City: Dhaka </br>';
  7. $output .= 'Country: Bangladesh </br>';
  8. return $output;
  9. }

Erase code after opening brace { and before ending } brace and write :

  1. /**
  2.  * menu callback; person add form
  3.  */
  4. function person_personal_info(){
  5. // drupal_get_form($form_id)
  6. // $form_id: The unique string identifying the desired form
  7. $output = drupal_get_form('person_add_form');
  8. return $output;
  9. }

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

  1. /**
  2.  * form builder; person add form
  3.  */
  4. function person_add_form($form_state){
  5.  
  6. // drupal_set_title('Add New Person');
  7. $form = array();
  8.  
  9. $form['name'] = array(
  10. '#title' => 'Your Name',
  11. '#type' => 'textfield',
  12. '#size' => '30',
  13. );
  14.  
  15. $form['city'] = array(
  16. '#title' => 'Your City',
  17. '#type' => 'textfield',
  18. '#size' => '30',
  19. );
  20.  
  21. $form['country'] = array(
  22. '#title' => 'Your Country',
  23. '#type' => 'textfield',
  24. '#size' => '30',
  25. );
  26.  
  27. $form['submit'] = array(
  28. '#type' => 'submit',
  29. '#value' => 'Submit',
  30. );
  31.  
  32. return $form;
  33. }

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

  1. drupal_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

  1. /**
  2.  * validate function for person add form
  3.  *
  4.  * @param $form An associative array containing the structure of the form
  5.  * @param $form_state A keyed array containing the current state of the form
  6.  */
  7. function person_add_form_validate($form,$form_state){
  8. // display a sample message that, our form is submitted
  9. drupal_set_message('validate function called successfully.');
  10. }

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

  1. // helper function to display form data
  2. function pretty_print($data=''){
  3. drupal_set_message('<pre>' . print_r($data,true) . '</pre>');
  4. }

Add the newly created pretty_print() to person_add_form_validate()

  1. /**
  2.  * validate function for person add form
  3.  *
  4.  * @param $form An associative array containing the structure of the form
  5.  * @param $form_state A keyed array containing the current state of the form
  6.  */
  7. function person_add_form_validate($form,$form_state){
  8. // display a sample message that, our form is submitted
  9. drupal_set_message('validate function called successfully.');
  10. pretty_print($form_state); // to display form submitted data
  11. }

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:

  1. $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

  1. /**
  2.  * validate function for person add form
  3.  *
  4.  * @param $form An associative array containing the structure of the form
  5.  * @param $form_state A keyed array containing the current state of the form
  6.  */
  7. function person_add_form_validate($form,$form_state){
  8. // display a sample message that, our form is submitted
  9. // drupal_set_message('validate function called successfully.');
  10. // pretty_print($form_state);
  11.  
  12. $name = $form_state['values']['name'];
  13. if (trim($name) == '' || strlen(trim($name)) < 6 ){
  14. form_set_error('name','Person Name is either empty or Less than 6 characters.');
  15. }
  16. }

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

  1. CREATE TABLE `person` (
  2. `pid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  3. `name` VARCHAR(50) NOT NULL,
  4. `city` VARCHAR(50) NOT NULL,
  5. `country` VARCHAR(50) NOT NULL,
  6. PRIMARY KEY (`pid`)
  7. ) ENGINE=INNODB DEFAULT CHARSET=latin1

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

  1. /**
  2.  * submit function for person add form
  3.  *
  4.  * @param $form An associative array containing the structure of the form
  5.  * @param $form_state A keyed array containing the current state of the form
  6.  */
  7. function person_add_form_submit($form,$form_state){
  8. $name = trim($form_state['values']['name']);
  9. $city = trim($form_state['values']['city']);
  10. $country = trim($form_state['values']['country']);
  11. $query = "INSERT INTO person (`name`,city,country) VALUES ('%s', '%s', '%s')";
  12. $result = db_query($query, $name, $city, $country);
  13. if ($result !== FALSE){
  14. drupal_set_message('data saved successfully.');
  15. }
  16. }

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.

Tags

Comments

Do you have a Drupal 7 version of this excellent tutorial, or does it still apply to D7?

Post new comment

The content of this field is kept private and will not be shown publicly.
Max length 128 characters
Image CAPTCHA
Enter the characters shown in the image.

About This Mania

Hasan Hafiz, Blogger at web mania ltd (www.webemania.com). He has more than 5 years experience in web development platform. He worked as a Sr. Software Developer at Canadian based outsourcing software firm, Lead Developer at countries top most VOIPswitch development company and Sr. Software Engineer at USA based outsourcing software firm . His expertise areas are PHP, MySQL, CSS, Javascript, JQuery, HTML, XML and MVC Framework Codeigniter. He has been along with Drupal from more than 4 years. You may call him Drupal Addicted.