Drupal 7: how to create a form within a module

Drupal If you develop modules and you need to create a form in one of your page, there is a nice Drupal function that can render an array into a pretty HTML form: drupal_get_form().

This handy function is usually needed in a menu callback as it does not require an existing form.

You can use it like this:

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
 $items['mymodule'] = array(
  'title' => 'My title', //The name of the menu that will be displayed
  'page callback' => 'mymodule_page_callback', //The name of the function that will output a page
 );
 return $items;
}

function mymodule_page_callback() {
 //The argument is the name of the function with the form details
 return drupal_get_form('mymodule_form');
}

function mymodule_form($form, &$form_state) {
 $form = array (
  //The action attribute of the HTML form tag
  '#action' => '#', 
  //We define a simple text field for the "name"
  'name' => array ( 
   '#type' => 'textfield',
   //The label that will be placed with the field
   '#title' => t('My pretty name'),
   //The description will be placed right below the field
   '#description' => t('My descrition'),
   //If true the system will perform a simple check on submit so that it is never empty
   '#required' => TRUE,
  ),
  //We define a simple submit button
  'submit' => array ( 
   '#type' => 'submit',
   '#value' => t('My submit'),
  ),
 );
 
 return $form;
}

After you have defined the form, you can implement 2 extra functions that will handle the validation (_validate) and the processing (_submit) of the form values.

function mymodule_form_validate($form, &$form_state){
 // My validation parameters
 if(strlen($form_state['values']['name']) > 10) {
  form_set_error('', t('Hey, your name is too long!'));
 }
}

function mymodule_form_submit($form, &$form_state) {
 //My success processing
 drupal_set_message(t('Yay, your name is fine!'));
}

And that is, pretty simple uh?

2013 10 10 Edit: Updated with the syntax highlighter!

Advertisements