Form generation

Functions to enable the processing and display of HTML forms.

Drupal uses these functions to achieve consistency in its form processing and presentation, while simplifying code and reducing the amount of HTML that must be explicitly generated by modules.

The primary function used with forms is drupal_get_form(), which is used for forms presented interactively to a user. Forms can also be built and submitted programmatically without any user input using the drupal_form_submit() function.

drupal_get_form() handles retrieving, processing, and displaying a rendered HTML form for modules automatically.

Here is an example of how to use drupal_get_form() and a form builder function:

<?php

$form = drupal_get_form('my_module_example_form');
...
function my_module_example_form($form, &$form_state) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function my_module_example_form_validate($form, &$form_state) {
// Validation logic.
}
function my_module_example_form_submit($form, &$form_state) {
// Submission logic.
}

?>

Or with any number of additional arguments:

<?php

$extra = "extra";
$form = drupal_get_form('my_module_example_form', $extra);
...
function my_module_example_form($form, &$form_state, $extra) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => $extra,
);
return $form;
}

?>

The $form argument to form-related functions is a structured array containing the elements and properties of the form. For information on the array components and format, and more detailed explanations of the Form API workflow, see the Form API reference and the Form API section of the handbook. In addition, there is a set of Form API tutorials in the Form Example Tutorial which provide basics all the way up through multistep forms.

In the form builder, validation, submission, and other form functions, $form_state is the primary influence on the processing of the form and is passed by reference to most functions, so they use it to communicate with the form system and each other.

The $form_state keys are:

  • 'values': An associative array of values submitted to the form. The validation functions and submit functions use this array for nearly all their decision making. (Note that #tree determines whether the values are a flat array or an array whose structure parallels the $form array.)
  • 'rebuild': If the submit function sets $form_state['rebuild'] to TRUE, submission is not completed and instead the form is rebuilt using any information that the submit function has made available to the form builder function via $form_state. This is commonly used for wizard-style multi-step forms, add-more buttons, and the like. For further information see drupal_build_form().
  • 'redirect': a URL that will be used to redirect the form on submission. See drupal_redirect_form() for complete information.
  • 'storage': $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API, but by tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.
  • 'temporary': Since values for all non-reserved keys in $form_state persist throughout a multistep form sequence, the Form API provides the 'temporary' key for modules to use for communicating information across form-related functions during a single page request only. There is no use-case for this functionality in core.
  • 'triggering_element': (read-only) The form element that triggered submission. This is the same as the deprecated $form_state['clicked_button']. It is the element that caused submission, which may or may not be a button (in the case of AJAX forms.) This is often used to distinguish between various buttons in a submit handler, and is also used in AJAX handlers.
  • 'cache': The typical form workflow involves two page requests. During the first page request, a form is built and returned for the user to fill in. Then the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. In some special use-cases, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. A form builder function can set 'cache' to TRUE to do this. One example where this is needed is to handle AJAX submissions, so ajax_process_form() sets this for all forms that include an element with a #ajax property. (In AJAX, the handler has no way to build the form itself, so must rely on the cached version created on each page load, so it's a classic example of this use case.) Note that the persistence of $form and $form_state across successive submissions of a multi-step form happens automatically regardless of the value for 'cache'.
  • 'input': The array of values as they were submitted by the user. These are raw and unvalidated, so should not be used without a thorough understanding of security implications. In almost all cases, code should use the data in the 'values' array exclusively. The most common use of this key is for multi-step forms that need to clear some of the user input when setting 'rebuild'.

Functions

NameLocationDescription
date_validatedrupal-7/includes/form.incValidates the date type to stop dates like February 30, 2006.
drupal_build_formdrupal-7/includes/form.incBuild and process a form based on a form id.
drupal_form_submitdrupal-7/includes/form.incRetrieves, populates, and processes a form.
drupal_get_formdrupal-7/includes/form.incWrapper for drupal_build_form() for use when $form_state is not needed.
drupal_prepare_formdrupal-7/includes/form.incPrepares a structured form array by adding required elements, executing any hook_form_alter functions, and optionally inserting a validation token to prevent tampering.
drupal_process_formdrupal-7/includes/form.incProcesses a form submission.
drupal_rebuild_formdrupal-7/includes/form.incRetrieves a form, caches it and processes it again.
drupal_redirect_formdrupal-7/includes/form.incRedirects the user to a URL after a form has been processed.
drupal_retrieve_formdrupal-7/includes/form.incRetrieves the structured array that defines a given form.
drupal_validate_formdrupal-7/includes/form.incValidates user-submitted form data from the $form_state using the validate functions defined in a structured form array.
form_builderdrupal-7/includes/form.incWalk through the structured form array, adding any required properties to each element and mapping the incoming input data to the proper elements. Also, execute any #process handlers attached to a specific element.
form_clear_errordrupal-7/includes/form.incClear all errors against all form elements made by form_set_error().
form_errordrupal-7/includes/form.incFlag an element as having an error.
form_execute_handlersdrupal-7/includes/form.incA helper function used to execute custom validation and submission handlers for a given form. Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
form_get_cachedrupal-7/includes/form.incFetch a form from cache.
form_get_errordrupal-7/includes/form.incReturn the error message filed against the form with the specified name.
form_get_errorsdrupal-7/includes/form.incReturn an associative array of all errors.
form_get_optionsdrupal-7/includes/form.incTraverses a select element's #option array looking for any values that hold the given key. Returns an array of indexes that match.
form_options_flattendrupal-7/includes/form.incAllows PHP array processing of multiple select options with the same value.
form_pre_render_conditional_form_elementdrupal-7/includes/form.incAdd form_element theming to an element if title or description is set.
form_pre_render_fieldsetdrupal-7/includes/form.incAdds members of this group as actual elements for rendering.
form_process_actionsdrupal-7/includes/form.incProcesses a form actions container element.
form_process_containerdrupal-7/includes/form.incProcesses a container element.
form_process_datedrupal-7/includes/form.incRoll out a single date element.
form_process_fieldsetdrupal-7/includes/form.incAdds fieldsets to the specified group or adds group members to this fieldset.
form_process_password_confirmdrupal-7/includes/form.incExpand a password_confirm field into two text boxes.
form_process_radiosdrupal-7/includes/form.incRoll out a single radios element to a list of radios, using the options array as index.
form_process_tableselectdrupal-7/includes/form.incCreate the correct amount of checkbox or radio elements to populate the table.
form_process_vertical_tabsdrupal-7/includes/form.incCreates a group formatted as vertical tabs.
form_process_weightdrupal-7/includes/form.incExpand weight elements into selects.
form_select_optionsdrupal-7/includes/form.incConverts a select form element's options array into an HTML.
form_set_cachedrupal-7/includes/form.incStore a form in the cache.
form_set_errordrupal-7/includes/form.incFiles an error against a form element.
form_set_valuedrupal-7/includes/form.incChange submitted form values during form validation.
form_state_defaultsdrupal-7/includes/form.incRetrieve default values for the $form_state array.
form_state_keys_no_cachedrupal-7/includes/form.incReturns an array of $form_state keys that shouldn't be cached.
form_state_values_cleandrupal-7/includes/form.incRemoves internal Form API elements and buttons from submitted form values.
form_type_checkboxes_valuedrupal-7/includes/form.incHelper function to determine the value for a checkboxes form element.
form_type_checkbox_valuedrupal-7/includes/form.incHelper function to determine the value for a checkbox form element.
form_type_image_button_valuedrupal-7/includes/form.incHelper function to determine the value for an image button form element.
form_type_password_confirm_valuedrupal-7/includes/form.incHelper function to determine the value for a password_confirm form element.
form_type_select_valuedrupal-7/includes/form.incHelper function to determine the value for a select form element.
form_type_textfield_valuedrupal-7/includes/form.incHelper function to determine the value for a textfield form element.
form_type_token_valuedrupal-7/includes/form.incHelper function to determine the value for form's token value.
map_monthdrupal-7/includes/form.incHelper function for usage with drupal_map_assoc to display month names.
password_confirm_validatedrupal-7/includes/form.incValidate password_confirm element.
theme_buttondrupal-7/includes/form.incReturns HTML for a button form element.
theme_checkboxdrupal-7/includes/form.incReturns HTML for a checkbox form element.
theme_checkboxesdrupal-7/includes/form.incReturns HTML for a set of checkbox form elements.
theme_containerdrupal-7/includes/form.incReturns HTML for a container for grouped form items.
theme_datedrupal-7/includes/form.incReturns HTML for a date selection form element.
theme_fieldsetdrupal-7/includes/form.incReturns HTML for a fieldset form element and its children.
theme_filedrupal-7/includes/form.incReturns HTML for a file upload form element.
theme_formdrupal-7/includes/form.incReturns HTML for a form.
theme_form_elementdrupal-7/includes/form.incReturns HTML for a form element.
theme_form_element_labeldrupal-7/includes/form.incReturns HTML for a form element label and required marker.
theme_form_required_markerdrupal-7/includes/form.incReturns HTML for a marker for required form elements.
theme_hiddendrupal-7/includes/form.incReturns HTML for a hidden form element.
theme_image_buttondrupal-7/includes/form.incReturns HTML for an image button form element.
theme_passworddrupal-7/includes/form.incReturns HTML for a password form element.
theme_radiodrupal-7/includes/form.incReturns HTML for a radio button form element.
theme_radiosdrupal-7/includes/form.incReturns HTML for a set of radio button form elements.
theme_selectdrupal-7/includes/form.incReturns HTML for a select form element.
theme_submitdrupal-7/includes/form.incReturns HTML for a submit button form element.
theme_tableselectdrupal-7/includes/form.incReturns HTML for a table with radio buttons or checkboxes.
theme_textareadrupal-7/includes/form.incReturns HTML for a textarea form element.
theme_textfielddrupal-7/includes/form.incReturns HTML for a textfield form element.
theme_vertical_tabsdrupal-7/includes/form.incReturns HTML for an element's children fieldsets as vertical tabs.
weight_valuedrupal-7/includes/form.incIf no default value is set for weight select boxes, use 0.
_form_builder_handle_input_elementdrupal-7/includes/form.incPopulate the #value and #name properties of input elements so they can be processed and rendered.
_form_button_was_clickeddrupal-7/includes/form.incHelper function to handle the convoluted logic of button click detection.
_form_element_triggered_scripted_submissiondrupal-7/includes/form.incHelper function to handle the convoluted logic of button click detection.
_form_options_flattendrupal-7/includes/form.incHelper function for form_options_flatten().
_form_set_classdrupal-7/includes/form.incSets a form element's class attribute.
_form_set_valuedrupal-7/includes/form.incHelper function for form_set_value() and _form_builder_handle_input_element().
_form_validatedrupal-7/includes/form.incPerforms validation on form elements. First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validators.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options