Form generation

  1. drupal
    1. 6 includes/form.inc
    2. 7 includes/form.inc
    3. 8 core/includes/form.inc

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:

$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:

$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 documentation section. 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.

See drupal_build_form() for documentation of $form_state keys.

Functions & methods

NameDescription
date_validateValidates the date type to prevent invalid dates (e.g., February 30, 2006).
drupal_build_formBuilds and process a form based on a form id.
drupal_form_submitRetrieves, populates, and processes a form.
drupal_get_formReturns a renderable form array for a given form ID.
drupal_prepare_formPrepares a structured form array.
drupal_process_formProcesses a form submission.
drupal_rebuild_formConstructs a new $form from the information in $form_state.
drupal_redirect_formRedirects the user to a URL after a form has been processed.
drupal_retrieve_formRetrieves the structured array that defines a given form.
drupal_validate_formValidates user-submitted form data in the $form_state array.
element_validate_integerForm element validation handler for integer elements.
element_validate_integer_positiveForm element validation handler for integer elements that must be positive.
element_validate_numberForm element validation handler for number elements.
form_builderBuilds and processes all elements in the structured form array.
form_clear_errorClears all errors against all form elements made by form_set_error().
form_errorFlags an element as having an error.
form_execute_handlersExecutes custom validation and submission handlers for a given form.
form_get_cacheFetches a form from cache.
form_get_errorReturns the error message filed against the given form element.
form_get_errorsReturns an associative array of all errors.
form_get_optionsReturns the indexes of a select element's options matching a given key.
form_load_includeEnsures an include file is loaded loaded whenever the form is processed.
form_options_flattenAllows PHP array processing of multiple select options with the same value.
form_pre_render_conditional_form_elementAdds form element theming to an element if its title or description is set.
form_pre_render_fieldsetAdds members of this group as actual elements for rendering.
form_process_actionsProcesses a form actions container element.
form_process_checkboxSets the #checked property of a checkbox element.
form_process_checkboxesProcesses a checkboxes form element.
form_process_containerProcesses a container element.
form_process_dateExpands a date element into year, month, and day select elements.
form_process_fieldsetArranges fieldsets into groups.
form_process_machine_nameProcesses a machine-readable name form element.
form_process_password_confirmExpand a password_confirm field into two text boxes.
form_process_radiosExpands a radios element into individual radio elements.
form_process_selectProcesses a select list form element.
form_process_tableselectCreates checkbox or radio elements to populate a tableselect table.
form_process_vertical_tabsCreates a group formatted as vertical tabs.
form_process_weightExpands a weight element into a select element.
form_select_optionsConverts a select form element's options array into HTML.
form_set_cacheStores a form in the cache.
form_set_errorFiles an error against a form element.
form_set_valueChanges submitted form values during form validation.
form_state_defaultsRetrieves default values for the $form_state array.
form_state_keys_no_cacheReturns an array of $form_state keys that shouldn't be cached.
form_state_values_cleanRemoves internal Form API elements and buttons from submitted form values.
form_type_checkboxes_valueDetermines the value for a checkboxes form element.
form_type_checkbox_valueDetermines the value for a checkbox form element.
form_type_image_button_valueDetermines the value for an image button form element.
form_type_password_confirm_valueDetermines the value for a password_confirm form element.
form_type_radios_valueForm value callback: Determines the value for a #type radios form element.
form_type_select_valueDetermines the value for a select form element.
form_type_tableselect_valueDetermines the value for a tableselect form element.
form_type_textfield_valueDetermines the value for a textfield form element.
form_type_token_valueDetermines the value for form's token value.
form_validate_machine_nameForm element validation handler for machine_name elements.
map_monthHelper function for usage with drupal_map_assoc to display month names.
password_confirm_validateValidates a password_confirm element.
theme_buttonReturns HTML for a button form element.
theme_checkboxReturns HTML for a checkbox form element.
theme_checkboxesReturns HTML for a set of checkbox form elements.
theme_containerReturns HTML to wrap child elements in a container.
theme_dateReturns HTML for a date selection form element.
theme_fieldsetReturns HTML for a fieldset form element and its children.
theme_fileReturns HTML for a file upload form element.
theme_formReturns HTML for a form.
theme_form_elementReturns HTML for a form element.
theme_form_element_labelReturns HTML for a form element label and required marker.
theme_form_required_markerReturns HTML for a marker for required form elements.
theme_hiddenReturns HTML for a hidden form element.
theme_image_buttonReturns HTML for an image button form element.
theme_passwordReturns HTML for a password form element.
theme_radioReturns HTML for a radio button form element.
theme_radiosReturns HTML for a set of radio button form elements.
theme_selectReturns HTML for a select form element.
theme_submitReturns HTML for a submit button form element.
theme_tableselectReturns HTML for a table with radio buttons or checkboxes.
theme_textareaReturns HTML for a textarea form element.
theme_textfieldReturns HTML for a textfield form element.
theme_vertical_tabsReturns HTML for an element's children fieldsets as vertical tabs.
weight_valueSets the value for a weight element, with zero as a default.
_form_builder_handle_input_elementAdds the #name and #value properties of an input element before rendering.
_form_button_was_clickedDetermines if a given button triggered the form submission.
_form_element_triggered_scripted_submissionDetects if an element triggered the form submission via Ajax.
_form_options_flattenIterates over an array and returns a flat array with duplicate keys removed.
_form_set_classSets a form element's class attribute.
_form_validatePerforms validation on form elements.

File

includes/form.inc, line 26
Functions for form and batch generation and processing.

Comments

drupal_render

You can use drupal_render($form) to print a form directly to a page if you have fetched it using drupal_get_form(mymodule_form).

Keep in mind that it is more advised to return the form and let the page builder render them in D7, instead of printing content directly to the page.

Form redirect with an "a name" HTML tag

If you want to redirect a form to a URL with an "A" element such as:

<A name="section1">Introduction</A>

You need to set the form_state['redirect'] call like so:

<?php
$form_state
['redirect'] = array('somepath/somefile'. $dHashID, array('fragment' => 'section1'));
?>

I needed this funcionality when using jQuery UI tabs.

Mitch Schwenk

On a broader note, when

On a broader note, when $form_state['redirect'] is an array it should be populated with arguments appropriate for drupal_goto() - which is to say, the second element in the array can itself be an array holding all the properties expected by url()'s $options argument, including fragment, query, absolute, etc.

Multistep form

If needed build multistep form, then necessary to specify in $form_state the 'rebuild' value as TRUE:

<?php
function my_form_submit($form, &$form_state) {
...
 
$form_state['rebuild'] = TRUE
...
}
?>

How to set the uid value at Validation

I tried bunch of things but nothing changes the uid.
I know i am getting drupal messages when opening the form and submitting the form but uid values are same.

<?php

function extra_form_alter(&$form, &$form_state, $form_id) {
    switch(
$form_id){
        case
'page_node_form':
                
       
drupal_set_message('Hey, we\'ve tapped into this form!'); 
       
$form['#validate'][] = 'node_validate_custom';
        break;

    }
}

function
node_validate_custom($form, &$form_state){
// ... Validation Code
       
$a = 3;
       
//form_set_value( $form['uid'], $a, $form_state);
           
       
$form['uid']['#value'] = 3;
       
drupal_set_message('Hey, we\'ve tapped into validator too form!'); 
       
    return
$form;
// ... Other Code
}
?>

form theming

To direct to the theme function, don't include '_theme':

$form['#theme'] = 'function_name';

IN hook_theme, you don't use 'variables', use 'render element' in order to get $form into the theming function:

function mymodule_theme($existing, $type, $theme, $path)  {
  return array(
    'function_name' => array(
      'render element' => 'form',
    ),
  );
}

Validate usage example

function my_module_example_form_validate($form, &$form_state) {
  $input_value_we_are_checking = $form_state['values']['the_field_name'];
  if(!my_function_checking_if_this_is_okay($input_value_we_are_checking)){
    form_set_error('the_field_name', 'WRONG! Try again!');
  }
}

function my_function_checking_if_this_is_okay($value_to_check){
  if($value_to_check == "badonkadonk"){
    return TRUE;
  }else{
    return FALSE;
  }
}

Timberland roll-top

Timberland roll-top Timberlands For Men boots is made of good quality material ,it can keep your feet dry, whatever the elements throw at you. as we introduce it ,now more and Cheap Timberlands more customer become love it . These boots can keep dry, stable and comfortable under any circumstances. Timberland boots women also allow people to show their high performances with defferent styles of clothing. so it is mix with the good quality and fashion ,it is a good choice for you .

Timberland Boots are fashion Shoes Timberland and stylish. This kind of Shoes Timberland can protect your ankle from hurt. Timberland Roll-top Boots with rubber lug outsole for traction and durability.Timberland men You will enjoy the wonderful comfortable and relaxed all the time.So wonderful! Timberland women no miss it .

good quality with big discount now for you .on our store have a lot of discount timberland shoes for you . you can come to check it . Timberland kids you may like some styles also .hope http://www.timberlanddiscounted.com/ you have a good time when shopping on our store.

prada high top sneaker

To learn more cheap prada shoes about the latest It Bag and see how even a man looks amazing carrying it read more contact prada looks just as good carrying the over-sized beauty.prada men shoes Also like this series prada handbag's Florence Welch, as Florence http://www.buycheappradashoessale.com/ And The Machine lead singer of the Brit won the "Best critics award."

"THE MASK" This film makes "sexy girl" Cameron prada high top sneaker Diaz come to the fore, became the eye of the star. Since then Cameron has entered a new area. Becoming the most red of the U.S. film actress and a chicago the devil Prada Men wears prada nomination. She is very popular winter series of leather Men Canvas Prada handbag.

It may be identical proud instant Men Casual Shoes for each of the ladies, who possess the zeal for custom Men Sneakers made handbags, once they are carrying cheap prada High Top Men Sneakers handbags. The meaning of the custom made Patent Leather Shoes bag to some lady may properly be considered a little something not fast for just about any dude to truly understand.

Login or register to post comments