wesley tanaka

Creating a new form element: hook_elements

Step 1. Defining the form element template

hook_elements should return an array. a key in this returned array is the name of the newly defined form element, and its associated value is the template used to create new form elements of this type. In this example, the module mymodule defines a new form element stringlist

function mymodule_elements()
{
$type = array();
$type['hifield'] = array(
'#default_value' => 'hi',
'#input' => TRUE,
'#process' => array('_stringlist_process' => array()),
);
return $type;
}

Step 2. Controlling the display of your new form element

There are three ways to describe how your form element is rendered into a form:

  • #theme: You can set a form element's #theme. For example, if you set $element['#theme'] to 'froggy', the element will be rendered with a call to theme('froggy', $element);
  • #theme_used: You can set a form element's #theme_used to FALSE, in which case, all of its children will be rendered in a default fashion
  • theme function: if neither of the above options are used, then theme('elementname', $element) is used by default.
If none of these mechanisms are used, a form element's children do not get rendered.

Some keys useful in defining a new element:

  • (Drupal 6) '#process' => array('func1', 'func2', ...): a list of functions to call. These functions get called before the form is displayed, and can be used to create a compound element made out of several primitive form elements (like 'date', 'checkboxes'), or to make a multi-stage form element. Each function given gets called from _form_builder_handle_input_element in includes/form.inc as func1($element, $edit, $form_state, $complete_form)

    When a form containing the custom element is is initially loaded, $element['#value'] and $edit are unset.

    When a form is being previewed or submitted, $edit contains the values submitted from the web browser, as does $element['#value'], unless it's been changed by another module.

    The #process function can make changes to $element['#value'] to change the structure or content of the value of the form element.

  • '#validate' => array('validate_func'
Syndicate content