Beginners guide

Last modified: May 7, 2009 - 20:01

The Drupal form API gives a module a way to define a form via a structured array, render it into HTML, handle validation and submission, and expose the form for other modules to alter.

There are three basic steps needed to make this happen:

  1. Choose a unique identifier (letters, numbers, and underscores, typically starting with the module prefix) for your form; for example, "my_module_my_form". This is known as the form ID.
  2. Define a form builder function (see below), which returns a structured array that defines the components of your form.
  3. In your module, where you want the form to appear, use the function drupal_get_form($form_id) to tell Drupal to retrieve and render the form. drupal_get_form() will call the form builder function you defined, and then transform the form array into HTML. As an example, see contact_site_page(), which is the function that displays the site-wide contact form for the Contact module.

Form builder function

The form builder function is a PHP function in your module, whose name is the same as the form ID you chose. (Technically, you can choose a different constructor function name if you implement hook_forms(), but usually this is not necessary.) The return value of your form builder function is an array that describes your form. Here is the simplest possible example, which describes an empty form:

<?php
function my_module_my_form($form_state) {
 
$form = array();
 
 
// This is where form elements etc. get added
 
 
return $form;
}
?>

The pages below show you examples of components you can add to the $form array. Once you get used to the syntax, the Form API Reference has a more complete list.

 
 

Drupal is a registered trademark of Dries Buytaert.