Form generation


Functions

 drupal_get_form ($form_id)
 drupal_rebuild_form ($form_id, &$form_state, $args, $form_build_id=NULL)
 form_set_cache ($form_build_id, $form, $form_state)
 form_get_cache ($form_build_id, &$form_state)
 drupal_execute ($form_id, &$form_state)
 drupal_retrieve_form ($form_id, &$form_state)
 drupal_process_form ($form_id, &$form, &$form_state)
 drupal_prepare_form ($form_id, &$form, &$form_state)
 drupal_validate_form ($form_id, $form, &$form_state)
 drupal_render_form ($form_id, &$form)
 drupal_redirect_form ($form, $redirect=NULL)
 _form_validate ($elements, &$form_state, $form_id=NULL)
 form_execute_handlers ($type, &$form, &$form_state)
 form_set_error ($name=NULL, $message= '', $reset=FALSE)
 form_get_errors ()
 form_get_error ($element)
 form_error (&$element, $message= '')
 form_builder ($form_id, $form, &$form_state)
 _form_builder_handle_input_element ($form_id, &$form, &$form_state, $complete_form)
 _form_button_was_clicked ($form)
 _form_builder_ie_cleanup ($form, &$form_state)
 form_type_image_button_value ($form, $edit=FALSE)
 form_type_checkbox_value ($form, $edit=FALSE)
 form_type_checkboxes_value ($form, $edit=FALSE)
 form_type_password_confirm_value ($form, $edit=FALSE)
 form_type_select_value ($form, $edit=FALSE)
 form_type_textfield_value ($form, $edit=FALSE)
 form_type_token_value ($form, $edit=FALSE)
 form_set_value ($form_item, $value, &$form_state)
 _form_set_value (&$form_values, $form_item, $parents, $value)
 _element_info ($type, $refresh=NULL)
 form_options_flatten ($array, $reset=TRUE)
 form_select_options ($element, $choices=NULL)
 form_get_options ($element, $key)
 expand_password_confirm ($element)
 password_confirm_validate ($form, &$form_state)
 expand_date ($element)
 date_validate ($form)
 map_month ($month)
 weight_value (&$form)
 expand_radios ($element)
 form_expand_ahah ($element)
 expand_checkboxes ($element)
 process_weight ($element)
 _form_set_class (&$element, $class=array())
 form_clean_id ($id=NULL, $flush=FALSE)

Detailed Description

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 drupal_get_form() function handles retrieving, processing, and displaying a rendered HTML form for modules automatically. For example:

 // Display the user registration form.
 $output = drupal_get_form('user_register');

Forms can also be built and submitted programmatically without any user input using the drupal_execute() function.

For information on the format of the structured arrays used to define forms, and more detailed explanations of the Form API workflow, see the reference and the quickstart guide.


Function Documentation

_element_info ( type,
refresh = NULL 
)

Retrieve the default properties for the defined element type.

_form_builder_handle_input_element ( form_id,
&$  form,
&$  form_state,
complete_form 
)

Populate the value and name properties of input elements so they can be processed and rendered. Also, execute any process handlers attached to a specific element.

_form_builder_ie_cleanup ( form,
&$  form_state 
)

In IE, if only one submit button is present, AND the enter key is used to submit the form, no form value is sent for it and our normal button detection code will never detect a match. We call this function after all other button-detection is complete to check for the proper conditions, and treat the single button on the form as 'clicked' if they are met.

_form_button_was_clicked ( form  ) 

Helper function to handle the sometimes-convoluted logic of button click detection.

In Internet Explorer, if ONLY one submit button is present, AND the enter key is used to submit the form, no form value is sent for it and we'll never detect a match. That special case is handled by _form_builder_ie_cleanup().

_form_set_class ( &$  element,
class = array() 
)

Sets a form element's class attribute.

Adds 'required' and 'error' classes as needed.

Parameters:
&$element The form element.
$name Array of new class names to be added.

_form_set_value ( &$  form_values,
form_item,
parents,
value 
)

Helper function for form_set_value().

We iterate over $parents and create nested arrays for them in $form_state['values'] if needed. Then we insert the value into the right array.

_form_validate ( elements,
&$  form_state,
form_id = NULL 
)

Performs 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.

Parameters:
$elements An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. The current user-submitted data is stored in $form_state['values'], though form validation functions are passed an explicit copy of the values for the sake of simplicity. Validation handlers can also $form_state to pass information on to submit handlers. For example: $form_state['data_for_submision'] = $data; This technique is useful when validation requires file parsing, web service requests, or other expensive requests that should not be repeated in the submission step.
$form_id A unique string identifying the form for validation, submission, theming, and hook_form_alter functions.

date_validate ( form  ) 

Validates the date type to stop dates like February 30, 2006.

drupal_execute ( form_id,
&$  form_state 
)

Retrieves a form using a form_id, populates it with $form_state['values'], processes it, and returns any validation errors encountered. This function is the programmatic counterpart to drupal_get_form().

Parameters:
$form_id The unique string identifying the desired form. If a function with that name exists, it is called to build the form array. Modules that need to generate the same form (or very similar forms) using different $form_ids can implement hook_forms(), which maps different $form_id values to the proper form constructor function. Examples may be found in node_forms(), search_forms(), and user_forms().
$form_state A keyed array containing the current state of the form. Most important is the $form_state['values'] collection, a tree of data used to simulate the incoming $_POST information from a user's form submission.
... Any additional arguments are passed on to the functions called by drupal_execute(), including the unique form constructor function. For example, the node_edit form requires that a node object be passed in here when it is called. For example:
// register a new user $form_state = array(); $form_state['values']['name'] = 'robo-user'; $form_state['values']['mail'] = 'robouser.com'; $form_state['values']['pass'] = 'password'; $form_state['values']['op'] = t('Create new account'); drupal_execute('user_register', $form_state);

// Create a new node $form_state = array(); module_load_include('inc', 'node', 'node.pages'); $node = array('type' => 'story'); $form_state['values']['title'] = 'My node'; $form_state['values']['body'] = 'This is the body text!'; $form_state['values']['name'] = 'robo-user'; $form_state['values']['op'] = t('Save'); drupal_execute('story_node_form', $form_state, (object)$node);

drupal_get_form ( form_id  ) 

Retrieves a form from a constructor function, or from the cache if the form was built in a previous page-load. The form is then passesed on for processing, after and rendered for display if necessary.

Parameters:
$form_id The unique string identifying the desired form. If a function with that name exists, it is called to build the form array. Modules that need to generate the same form (or very similar forms) using different $form_ids can implement hook_forms(), which maps different $form_id values to the proper form constructor function. Examples may be found in node_forms(), search_forms(), and user_forms().
... Any additional arguments are passed on to the functions called by drupal_get_form(), including the unique form constructor function. For example, the node_edit form requires that a node object be passed in here when it is called.
Returns:
The rendered form.

drupal_prepare_form ( form_id,
&$  form,
&$  form_state 
)

Prepares a structured form array by adding required elements, executing any hook_form_alter functions, and optionally inserting a validation token to prevent tampering.

Parameters:
$form_id A unique string identifying the form for validation, submission, theming, and hook_form_alter functions.
$form An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. Passed in here so that hook_form_alter() calls can use it, as well.

drupal_process_form ( form_id,
&$  form,
&$  form_state 
)

This function is the heart of form API. The form gets built, validated and in appropriate cases, submitted.

Parameters:
$form_id The unique string identifying the current form.
$form An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. This includes the current persistent storage data for the form, and any data passed along by earlier steps when displaying a multi-step form. Additional information, like the sanitized $_POST data, is also accumulated here.

drupal_rebuild_form ( form_id,
&$  form_state,
args,
form_build_id = NULL 
)

Retrieves a form, caches it and processes it with an empty $_POST.

This function clears $_POST and passes the empty $_POST to the form_builder. To preserve some parts from $_POST, pass them in $form_state.

If your AHAH callback simulates the pressing of a button, then your AHAH callback will need to do the same as what drupal_get_form would do when the button is pressed: get the form from the cache, run drupal_process_form over it and then if it needs rebuild, run drupal_rebuild_form over it. Then send back a part of the returned form. $form_state['clicked_button']['array_parents'] will help you to find which part.

Parameters:
$form_id The unique string identifying the desired form. If a function with that name exists, it is called to build the form array. Modules that need to generate the same form (or very similar forms) using different $form_ids can implement hook_forms(), which maps different $form_id values to the proper form constructor function. Examples may be found in node_forms(), search_forms(), and user_forms().
$form_state A keyed array containing the current state of the form. Most important is the $form_state['storage'] collection.
$args Any additional arguments are passed on to the functions called by drupal_get_form(), plus the original form_state in the beginning. If you are getting a form from the cache, use $form['parameters'] to shift off the $form_id from its beginning then the resulting array can be used as $arg here.
$form_build_id If the AHAH callback calling this function only alters part of the form, then pass in the existing form_build_id so we can re-cache with the same csid.
Returns:
The newly built form.

drupal_redirect_form ( form,
redirect = NULL 
)

Redirect the user to a URL after a form has been processed.

Parameters:
$form An associative array containing the structure of the form.
$redirect An optional value containing the destination path to redirect to if none is specified by the form.

drupal_render_form ( form_id,
&$  form 
)

Renders a structured form array into themed HTML.

Parameters:
$form_id A unique string identifying the form for validation, submission, theming, and hook_form_alter functions.
$form An associative array containing the structure of the form.
Returns:
A string containing the themed HTML.

drupal_retrieve_form ( form_id,
&$  form_state 
)

Retrieves the structured array that defines a given form.

Parameters:
$form_id The unique string identifying the desired form. If a function with that name exists, it is called to build the form array. Modules that need to generate the same form (or very similar forms) using different $form_ids can implement hook_forms(), which maps different $form_id values to the proper form constructor function.
$form_state A keyed array containing the current state of the form.
... Any additional arguments needed by the unique form constructor function. Generally, these are any arguments passed into the drupal_get_form() or drupal_execute() functions after the first argument. If a module implements hook_forms(), it can examine these additional arguments and conditionally return different builder functions as well.

drupal_validate_form ( form_id,
form,
&$  form_state 
)

Validates user-submitted form data from the $form_state using the validate functions defined in a structured form array.

Parameters:
$form_id A unique string identifying the form for validation, submission, theming, and hook_form_alter functions.
$form An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. The current user-submitted data is stored in $form_state['values'], though form validation functions are passed an explicit copy of the values for the sake of simplicity. Validation handlers can also $form_state to pass information on to submit handlers. For example: $form_state['data_for_submision'] = $data; This technique is useful when validation requires file parsing, web service requests, or other expensive requests that should not be repeated in the submission step.

expand_date ( element  ) 

Roll out a single date element.

expand_password_confirm ( element  ) 

Expand a password_confirm field into two text boxes.

expand_radios ( element  ) 

Roll out a single radios element to a list of radios, using the options array as index.

form_builder ( form_id,
form,
&$  form_state 
)

Walk through the structured form array, adding any required properties to each element and mapping the incoming $_POST data to the proper elements.

Parameters:
$form_id A unique string identifying the form for validation, submission, theming, and hook_form_alter functions.
$form An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. In this context, it is used to accumulate information about which button was clicked when the form was submitted, as well as the sanitized $_POST data.

form_clean_id ( id = NULL,
flush = FALSE 
)

Prepare an HTML ID attribute string for a form item.

Remove invalid characters and guarantee uniqueness.

Parameters:
$id The ID to clean.
$flush If set to TRUE, the function will flush and reset the static array which is built to test the uniqueness of element IDs. This is only used if a form has completed the validation process. This parameter should never be set to TRUE if this function is being called to assign an ID to the ID element.
Returns:
The cleaned ID.

form_error ( &$  element,
message = '' 
)

Flag an element as having an error.

form_execute_handlers ( type,
&$  form,
&$  form_state 
)

A 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.

Parameters:
$type The type of handler to execute. 'validate' or 'submit' are the defaults used by Form API.
$form An associative array containing the structure of the form.
$form_state A keyed array containing the current state of the form. If the user submitted the form by clicking a button with custom handler functions defined, those handlers will be stored here.

form_expand_ahah ( element  ) 

Add AHAH information about a form element to the page to communicate with javascript. If ahah[path] is set on an element, this additional javascript is added to the page header to attach the AHAH behaviors. See ahah.js for more information.

Parameters:
$element An associative array containing the properties of the element. Properties used: ahah_event, ahah_path, ahah_wrapper, ahah_parameters, ahah_effect.
Returns:
None. Additional code is added to the header of the page using drupal_add_js.

form_get_cache ( form_build_id,
&$  form_state 
)

Fetch a form from cache.

form_get_error ( element  ) 

Return the error message filed against the form with the specified name.

form_get_errors (  ) 

Return an associative array of all errors.

form_get_options ( element,
key 
)

Traverses a select element's option array looking for any values that hold the given key. Returns an array of indexes that match.

This function is useful if you need to modify the options that are already in a form element; for example, to remove choices which are not valid because of additional filters imposed by another module. One example might be altering the choices in a taxonomy selector. To correctly handle the case of a multiple hierarchy taxonomy, options arrays can now hold an array of objects, instead of a direct mapping of keys to labels, so that multiple choices in the selector can have the same key (and label). This makes it difficult to manipulate directly, which is why this helper function exists.

This function does not support optgroups (when the elements of the options array are themselves arrays), and will return FALSE if arrays are found. The caller must either flatten/restore or manually do their manipulations in this case, since returning the index is not sufficient, and supporting this would make the "helper" too complicated and cumbersome to be of any help.

As usual with functions that can return array() or FALSE, do not forget to use === and !== if needed.

Parameters:
$element The select element to search.
$key The key to look for.
Returns:
An array of indexes that match the given $key. Array will be empty if no elements were found. FALSE if optgroups were found.

form_set_cache ( form_build_id,
form,
form_state 
)

Store a form in the cache.

form_set_error ( name = NULL,
message = '',
reset = FALSE 
)

File an error against a form element.

Parameters:
$name The name of the form element. If the parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the parents array starts with 'foo'.
$message The error message to present to the user.
$reset Reset the form errors static cache.
Returns:
Never use the return value of this function, use form_get_errors and form_get_error instead.

form_set_value ( form_item,
value,
&$  form_state 
)

Change submitted form values during the form processing cycle.

Use this function to change the submitted value of a form item in the validation phase so that it persists in $form_state through to the submission handlers in the submission phase.

Since $form_state['values'] can either be a flat array of values, or a tree of nested values, some care must be taken when using this function. Specifically, $form_item['parents'] is an array that describes the branch of the tree whose value should be updated. For example, if we wanted to update $form_state['values']['one']['two'] to 'new value', we'd pass in $form_item['parents'] = array('one', 'two') and $value = 'new value'.

Parameters:
$form_item The form item that should have its value updated. Keys used: parents, value. In most cases you can just pass in the right element from the $form array.
$value The new value for the form item.
$form_state The array where the value change should be recorded.

form_type_checkbox_value ( form,
edit = FALSE 
)

Helper function to determine the value for a checkbox form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_checkboxes_value ( form,
edit = FALSE 
)

Helper function to determine the value for a checkboxes form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_image_button_value ( form,
edit = FALSE 
)

Helper function to determine the value for an image button form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_password_confirm_value ( form,
edit = FALSE 
)

Helper function to determine the value for a password_confirm form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_select_value ( form,
edit = FALSE 
)

Helper function to determine the value for a select form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_textfield_value ( form,
edit = FALSE 
)

Helper function to determine the value for a textfield form element.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

form_type_token_value ( form,
edit = FALSE 
)

Helper function to determine the value for form's token value.

Parameters:
$form The form element whose value is being populated.
$edit The incoming POST data to populate the form element. If this is FALSE, the element's default value should be returned.
Returns:
The data that will appear in the $form_state['values'] collection for this element. Return nothing to use the default.

map_month ( month  ) 

Helper function for usage with drupal_map_assoc to display month names.

password_confirm_validate ( form,
&$  form_state 
)

Validate password_confirm element.

process_weight ( element  ) 

Expand weight elements into selects.

weight_value ( &$  form  ) 

If no default value is set for weight select boxes, use 0.