Community Documentation

Form API Quickstart Guide

Last updated May 20, 2011. Created by Steven Jones on November 2, 2005.
Edited by schure, jhodgdon, webchick, ax. Log in to edit this page.

[Maybe you are looking for the newer guide (Drupal 6, 7, 8...).]

The Drupal Form API provides sophisticated form techniques and also allows for almost unlimited possibilities for custom theming, validation, and execution of forms. Even better, ANY form (even those in core) can be altered in almost any way imaginable--elements can be removed, added, and rearranged. Perhaps most important, the Form API provides a secure framework for forms, protecting against many exploits, and the programmer has to do almost nothing to get this protection. This page is certainly not a comprehensive guide to this functionality, but should provide a good working foundation with which to do the most basic form creation, theming, validation, and execution. For programming details on form elements and their properties, please see the Forms API Reference.

Creating Forms

Form elements are now declared in array fashion, with the hierarchical structure of the form elements themselves as array elements (which can be nested), and each form elements properties/attributes listed as array elements in key/value pairs--the key being the name of the property/attribute, and the value being the value of the property/attribute. For example, here's how to go about constructing a textfield form element:

<?php
$form
['foo'] = array(
 
'#type' => 'textfield',
 
'#title' => t('bar'),
 
'#default_value' => $object['foo'],
 
'#size' => 60,
 
'#maxlength' => 64,
 
'#description' => t('baz'),
);
?>

and a submit button:

<?php
$form
['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
?>

A few things to note:

  1. The element's name property is declared in the $form array, at the very end of the array tree. For example, if an element in the form tree was structured like this:
    <?php
    $form
    ['account_settings']['username']
    ?>

    ...then that element's name property is 'username'--this is the key it will be available under in $_POST['edit'] (or $form_values, which is the array used in execute functions), as the form code flattens the array in this fashion before it passes the key/value pairs. NOTE: if you wish to have the full tree structure passed to $_POST['edit'] and $form_values, this is possible, and will be discussed later.
  2. The type of form element is declared as an attribute with the '#type' property.
  3. Properties/attributes keys are declared with surrounding quotes, beginning with a # sign. Values are strings.
  4. The order of the properties/attributes doesn't matter, and any attributes that you don't need don't need to be declared. Many properties/attributes also have a default fallback value if not explicitly declared.
  5. Don't use the '#value' attribute for any form elements that can be changed by the user. Use the '#default_value' attribute instead. Don't put values from $_POST here! FormsAPI will deal with that for you; only put the original value of the field here.

One of the greatest advantages of this system is you don't need to remember the order of arguments in form functions! Plus, the explicitly named keys make deciphering the form element much easier.

Let's take a look at a working piece of code using the API:

<?php
function test_form() {
 
// Access log settings:
 
$options = array('1' => t('Enabled'), '0' => t('Disabled'));
 
$form['access'] = array(
   
'#type' => 'fieldset',
   
'#title' => t('Access log settings'),
   
'#tree' => TRUE,
  );
 
$form['access']['log'] = array(
   
'#type' => 'radios',
   
'#title' => t('Log'),
   
'#default_value' =>variable_get('log', 0),
   
'#options' => $options,
   
'#description' => t('The log.'),
  );
 
$period = drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800), 'format_interval');
 
$form['access']['timer'] = array(
   
'#type' => 'select',
   
'#title' => t('Discard logs older than'),
   
'#default_value' => variable_get('timer', 259200),
   
'#options' => $period,
   
'#description' => t('The timer.'),
  );
 
// Description
 
$form['details'] = array(
   
'#type' => 'fieldset',
   
'#title' => t('Details'),
   
'#collapsible' => TRUE,
   
'#collapsed' => TRUE,
  );
 
$form['details']['description'] = array(
   
'#type' => 'textarea',
   
'#title' => t('Describe it'),
   
'#default_value' =>variable_get('description', ''),
   
'#cols' => 60,
   
'#rows' => 5,
   
'#description' => t('Log description.'),
  );
 
$form['details']['admin'] = array(
   
'#type' => 'checkbox',
   
'#title' => t('Only admin can view'),
   
'#default_value' => variable_get('admin', 0),
  );
 
$form['name'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Name'),
   
'#size' => 30,
   
'#maxlength' => 64,
   
'#description' => t('Enter the name for this group of settings'),
  );
 
$form['hidden'] = array('#type' => 'value', '#value' => 'is_it_here');
 
$form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
  return
$form;
}

function
test_page() {
   return
drupal_get_form('test_form');
}
?>

This example demonstrates how form elements can be built in a hierarchical fashion by expanding and layering the form array. There are two functions involved - the function that builds the form, and another that displays the form using drupal_get_form().

Notice that the first layer is made up of two form groups, 'access', and 'details', and that inside each of these groups, one layer down, are some individual form elements. Order of construction is important here, as the form building code will default to the constructed order of the $form array when it builds the form (this can be overridden, and will be discussed later in the custom theming section).

For form groups, the '#type' parameter is set to 'fieldset', and notice how the 'details' form group is made into a collapsed form group with the addition of a few attributes.

All groups/elements are been built into the master $form array by the builder function.

The drupal_get_form function is the "key" function in the Forms API. Note that in its basic usage, it takes just one argument, a string which
is both the form ID and also the name of the function that builds the $form array. drupal_get_form can take optional additional arguments, which will be simply passed on to the $form builder function.

drupal_get_form does the following:

  • Starts the entire form-building process by getting the $form from the builder function
  • Translates the $form['name'] items into actual form elements
  • Performs any validation and "clean-up" that needs to be done, and calls custom validation functions if declared
  • Submits the form if a submit function is declared, and the form has been submitted
  • Calls any custom theming functions that have been declared
  • Returns an HTML string which contains the actual form.

An important thing to note: notice that $form['access'] has a '#tree' => TRUE attribute. this setting retains the full tree structure for all elements under it when it is passed to $_POST['edit'] and $form_values. you must explicitly declare this anywhere you wish to retain an array's full hierarchy when it is passed.

Theming Forms

The API makes custom theming of all forms (including those found in core) possible. This custom theming becomes possible when all hard coded theming elements have been abstracted, so that they can be overridden at time of form generation. The abstraction is accomplished using one of the following two methods:

  1. Including any markup directly as an element in the $form array:
    • There are '#prefix' and '#suffix' attributes, and these will place the declared markup either before or after the form element in question. for example:
      <?php
      $form
      ['access'] = array(
       
      '#type' => 'fieldset',
       
      '#title' => t('Access log settings'),
       
      '#prefix' => '<div>',
       
      '#suffix' => '</div>'
      );
      ?>

      ...will place the div tags before and after the entire form group (meaning the form elements of the group will also be enclosed in the div). if you were to put those attributes in one of the form elements inside that form group, then they would only wrap that particular element, etc.

    • There is a '#markup' type which you can place anywhere in the form, and its value will be output directly in its specified location in the forms hierarchy when the form is rendered. example:
      <?php
      $form
      ['div_tag'] = array(
       
      '#type' => 'markup',
       
      '#value' => '<p>foo</p>',
      );
      ?>

      This markup form element can then be accessed/altered through its name in the array, 'div_tag'

      NOTE: it's not necessary to explicitly declare the type as markup, since type will default to markup if none is declared.

  2. Break out any markup into a separate theme function. This is the preferred method if the markup has any degree of complication. it is accomplished by creating a theme function with theme_ prepended to the name of the form ID that is to be themed. in cases where you want to use the same theming function for more than one form, you can include the optional callback arg in drupal_get_form--in which case the third arg of drupal_get_form will be a string containing the name of the callback function which the form building code will call, and the theming function will be theme_ prepended to the name of the callback.

    example:

    For our above form, we could create a custom theming function as follows:

    <?php
    function theme_test_form($form) {
     
    $output = '<div>';
     
    $output .= drupal_render($form['name']);
     
    $output .= '<br />foo<br />';
     
    $output .= drupal_render($form['access']);
     
    $output .= '<br />bar<br />';
     
    $output .= drupal_render($form['details']);
     
    $output .= '</div>';
     
    $output .= drupal_render($form);
      return
    $output;
    }
    ?>

    A few things to note:

    1. The theme function has one argument, which is the form array that it will theme
    2. You build and return an output string just as you would do in a regular theming function
    3. Form elements are rendered using the drupal_render function
    4. If you call drupal_render and pass it an array of elements (as in a fieldset), it will render all the elements in the passed array, in the order in which they were built in the form array.
    5. While the default order of rendering for a form is the order in which it was built, you can override that in the theme function by calling drupal_render for any element in the place where you would like it to be rendered. In the above example, this was done with $form['name'].
    6. The rendering code keeps track of which elements have been rendered, and will only allow them to be rendered once. Notice that drupal_render is called for the entire form array at the very end of the theming function, but it will only render the remaining unrendered element, which in this case is the submit button. calling drupal_render($form) is a common way to end a theming function, as it will then render any submit buttons and/or hidden fields that have been declared in the form in a single call.

Validating Forms

The form API has general form validation which it performs on all submitted forms. If there is additional validation you wish to perform on a submitted form, you can create a validation function. the name of the validation function is the form ID with _validate appended to it. the function has two args: $form_id and $form_values. $form_id is the form ID of the passed form, and $form_values are the form values which you may perform validation on.

Here's an example validation function for our example code:

<?php
function test_form_validate($form_id, $form_values) {
  if (
$form_values['name'] == '') {
   
form_set_error('', t('You must select a name for this group of settings.'));
  }
}
?>

Submitting Forms

The preferred method of submitting forms with the API is through the use of a form submit function. This has the same naming convention and arguments as the validation function, except _submit is appended instead. Any forms which are submitted from a button of type => 'submit' will be passed to their corresponding submit function if it is available. This method is more secure than grabbing $_POST['edit'] and using a switch statement.

example:

<?php
function test_form_submit($form_id, $form_values) {
 
db_query("INSERT INTO {table} (name, log, hidden) VALUES ('%s', %d, '%s')", $form_values['name'], $form_values['access']['log'],$form_values['hidden']);
 
drupal_set_message(t('Your form has been saved.'));
}
?>

a few things to note:

  1. A submit function is called only if a submit button was present and exists in the $_POST, and validation did not fail.
  2. The $form_values array will not usually have the same hierarchical structure as the constructed $form array (due to the flattening discussed previously), so be aware of what arrays have been flattened, and what arrays have retained their hierarchy by use of the tree => TRUE attribute. notice above that 'statistics_enable_access_log' belongs to a tree'd array, and the full array structure must be used to access the value.
  3. If a form has a submit function, then hidden form values are not needed. Instead, any values that you need to pass to $form_values can be declared in the $form array as such:
    <?php
       $form
    ['foo'] = array('#type' => 'value', '#value' => 'bar')
    ?>

    This is accessed in $form_values['foo'], with a value of bar. This method is preferred because the values are not sent to the browser.

  4. The return value of the _submit function will be the target of a drupal_goto; every form is redirected after a submit. If you return nothing, the form will simply be redirected to itself after a submit. It is polite to use drupal_set_message() to explain to the user that the submission was successful.

Understanding the Flow

A difficult concept with Forms API compared to the previous (Drupal 4.6) method of doing things is that the drupal_get_form() function handles both presenting and responding to the form. What this means is that the $form array you construct in your function will be built first when the form is presented, and again when the form is submitted. In the previous Drupal forms API, the check for 'submit' was done before calling any of the form_* functions, because those directly created the output.

The practical upshot to this is that many developers immediately find themselves asking the question of "where does my data get stored?". The answer is simply that it doesn't. You put your $form data together, perhaps loading your object from the database and filling in #default_values, the form builder then checks this against what was posted. What you gain from this, however, is that the FormsAPI can deal with your data securely. Faking a POST is much harder since it won't let values that weren't actually on the form come through to the $form_values in your submit function, and in your 'select' types, it will check to ensure that the value actually existed in the select and reject the form if it was not.

Comments

Nevets wrote a really good simple example

This example module by Nevets is very helpful
http://drupal.org/node/68159#comment-129394

This page has a good intro
http://api.drupal.org/api/file/developer/topics/forms_api.html/4.7

This page explains how to add content to the form when you view it again, based on information submitted
http://drupal.org/node/98009

Here is an example for 5
http://www.lullabot.com/articles/drupal_5_making_forms_that_display_thei...

this page explains how you call the form builder, and how that changed from 4.7 to 5
http://www.k4ml.com/node/208
but I think the author made one mistake. $form_id is the first argument

A consolidated version 5 example

I had a lot of trouble trying to piece together the threads above into a working version for Drupal 5 (especially as the link to the "Form API Quickstart Guide" goes to the API version 6 page by default). Anyway its working now so here it is:

<?php

/**
* A small example module of using the form api
* to display and process a form
* that is not used to extend the basic node content type
*
* In this sample the form collects two numbers
* and multiplies them together
*/


/**
* Implementation of hook_help().
*
* Throughout Drupal, hook_help() is used to display help text at the top of
* pages. Some other parts of Drupal pages get explanatory text from these hooks
* as well. We use it here to provide a description of the module on the
* module administration page.
*/
function myform_help($section) {
  switch (
$section) {
    case
'admin/modules#description':
     
// This description is shown in the listing at admin/modules.
     
return t('The myform module multiplies two numbers together.');
  }
}

/**
* Implementation of hook_perm().
*
*/
function myform_perm() {
  return array(
'mutiple numbers');
}

/**
* Implementation of hook_menu().
*
*/
function myform_menu($may_cache) {
 
$items = array();

   
$access = user_access('mutiple numbers');
  
  if (
$may_cache) {
     
// This determines the path used to show the form and also makes a menu entry
      // This first path is for the entry form
   
$items[] = array('path' => 'myform/sample', 'title' => t('sample form'),
     
'callback' => myform_edit, 'access' => $access);
    
   
// This path is for the routine that actually does the multplication
    // It is only setup as a callback (no menu entry)
   
$items[] = array('path' => 'myform/multiple', 'title' => t('Multiplication Results'),
     
'type' => MENU_CALLBACK, 'callback' => myform_multiple, 'access' => $access);
    }
  
    return
$items;
}

function
myform_build_form() {
   
$form = array();
  
   
// Build up the form
    // See api.drupal.org/api/4.7/file/developer/topics/forms_api.html (quickstart guide)
    // and api.drupal.org/api/4.7/file/developer/topics/forms_api_reference.html (forms api)
    // for more information on creating forms
  
   
$form['value1'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Value 1'),
     
'#size' => 4,
     
'#maxlength' => 4,
     
'#description' => t('The first value to perform the multiplication with.')
    );
  
   
$form['value2'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Value 2'),
     
'#size' => 4,
     
'#maxlength' => 4,
     
'#description' => t('The second value to perform the multiplication with.')
    );
  
   
// Make sure we have a submit button

   
$form['submit'] = array('#type' => 'submit', '#value' => t('Multiple values'));

  
   
// drupal_get_form produces the form
    // which return to the drupal system
    // which produces the page
  
    // The first parameter to drupal_get_form
    // is the form id.  It also determines the
    // default validation and submit function names
    //
    // In this case
    //    Validation: myform_sample_validate()
    //  Submit: my_form_submit()
  
    //return drupal_get_form('myform_sample', $form);
   
return $form;
}

function
myform_edit() {
  return
drupal_get_form('myform_build_form');
}

function
myform_build_form_validate($form_id, $form_values) {
    if ( !isset(
$form_values['value1']) ) {
       
form_set_error('value1', t('You must provide the first multiplication value.'));
    }
    else if ( !
is_numeric($form_values['value1']) ) {
       
form_set_error('value1', t('The first multiplication value must be a number.'));
    }  

    if ( !isset(
$form_values['value2']) ) {
       
form_set_error('value2', t('You must provide the second multiplication value.'));
    }
    else if ( !
is_numeric($form_values['value2']) ) {
       
form_set_error('value2', t('The second multiplication value must be a number.'));
    }  
}

function
myform_build_form_submit($form_id, $form_values) {
   
// Submit routines do not directly produce any output
    // They do something with the form values
    // which is typically to store them in the database
    // then return a path to determine what page is shown next
  
    // In this case the path constructe includes the two values
  
   
return 'myform/multiple/' . $form_values['value1'] . '/' . $form_values['value2'];
}
  

function
myform_multiple($value1, $value2) {
   
$output = '<p>';
   
$output .= $value1. ' * ' . $value2 . ' = ' . ($value1 * $value2);
   
$output .= '</p>';
  
    return
$output;
}
?>

About this page

Drupal version
Drupal 5.x

Archive

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.