Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Creating a builder function to generate a form

Last updated on
October 14, 2016 - 20:46

Form workflow usually follows these stages:

  1. Declaration of a form and its elements in a function
  2. Modification of existing forms with the FAPI hook system
  3. Theming of forms
  4. Form validation and submission

Forms are represented as arrays in form builder functions. Each item within the $form array on api.drupal.org corresponds either to a form element (an input or other HTML on the rendered form) or an element property (meta-data used by FAPI during the rendering or processing of elements). A property has a key name that begins with a "#", while an element does not.


In this example, we have a module named mymodule and we want to declare a form builder function in it. The form declaration function receives at least two parameters:

  • $form - An array of elements and element properties
  • &$form_state - An array containing information about the current state of this form while a user is filling it out and submitting it. Importantly, this includes the values that the user may have entered into the form.

This simple form has a text field for the user name and a submit button.

 *  Form constructor for the example form.
function mymodule_example_form($form, &$form_state) {
  // Provide a text field.
  $form['name'] = array(
    '#title' => t('Your full name'),
    '#type' => 'textfield',
    '#required' => TRUE,
  // Provide a submit button.
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Update search',
  return $form;

For more information on types of form elements and the properties they use, see the Form API Reference.

This form can be rendered using the drupal_render() function:

  $arr = drupal_get_form('mymodule_example_form');
  print drupal_render($arr);

Note: this example renders the form, but provides no processing for validation or submission. To continue, download the Examples for Developers set of modules and read the tutorials in the Form Example module.