18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Building an Admin Interface<br />

Each element is keyed by a unique string, which will become the element's name<br />

attribute when the form is rendered. This element is then assigned an array<br />

of attributes.<br />

For a complete matrix of all the form elements defined by <strong>Drupal</strong> as well<br />

as the properties each one implements, visit:<br />

http://api.drupal.org/api/drupal/developer--topics--<br />

forms_api_reference.html/7<br />

'#type' => 'textfield',<br />

The first attribute is '#type' which defines what form element will be rendered.<br />

All the standard HTML form elements have types, as well as some <strong>Drupal</strong>-specific<br />

elements defined. In this case we are creating a basic textfield.<br />

'#title' => t('Warning e-mail subject'),<br />

'#description' => t(<br />

'The subject of the e-mail which will be sent to users.'),<br />

The next two attributes, '#title' and '#description' define the element's label<br />

and an optional description.<br />

Any attribute that a standard HTML element has are available as Form API<br />

properties or attributes as well. For instance, see the following two lines of code.<br />

'#size' => 40,<br />

'#maxlength' => 120,<br />

As you would expect, these define the size and maxlength attributes of our text field.<br />

One of the nice things about Form API is that it will automatically validate many of<br />

the element's attributes when the form is submitted. In this case <strong>Drupal</strong> will throw<br />

an error if any text is submitted with a length greater than the element's maxlength.<br />

All this happens transparently with no extra code from the developer.<br />

Form API also adds some convenience properties for validation purposes,<br />

like '#required'.<br />

'#required' => TRUE,<br />

When '#required' is set to TRUE, <strong>Drupal</strong> will throw an error if the form is submitted<br />

without a value in that element. Required fields are also marked with an asterisk in<br />

their labels. Again, this happens transparently without any extra code. <strong>Drupal</strong> will<br />

even highlight the field when an error applies to it! This on-the-fly error handling and<br />

form validation is one of the reasons Form API is such a boon to developers. It really<br />

reduces the amount of drudgery involved in creating and handling HTML forms.<br />

[ 130 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!