18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7<br />

Exposing fields to the Form API with<br />

widgets<br />

Although fields can be stored anywhere (or at least anywhere for which we write<br />

a storage engine) and accessed in a variety of ways, by far the most common user<br />

workflow is to create and edit an entity containing fields using a form embedded in<br />

a web page. In <strong>Drupal</strong>, all forms shown to the user are controlled by the Form API,<br />

introduced in Chapter 5. The way the field system exposes itself to the Form API is<br />

through widgets.<br />

Widgets are simply Form API fragments that can get built into a larger form by<br />

<strong>Drupal</strong>. They can be very simple or very complex, depending on how we want<br />

to present information to the user. In fact, some of the greatest powers of widgets<br />

comes from the fact that the form elements the widget exposes do not have to map<br />

to the storage of the field type itself at all. Imagine, for example, a field that stored<br />

geographic points. While we could simply offer the user a series of text fields to enter<br />

X and Y values, it would be much nicer if we could offer them an interactive map<br />

to click on. The coordinate data would then get mapped back into X and Y values<br />

before it's stored, without the field itself being any the wiser. With widgets, we can<br />

do exactly that.<br />

Declaring a widget<br />

As with field types, widgets start with an info hook:<br />

function dimfield_field_widget_info() {<br />

return array(<br />

'dimfield_simple' => array(<br />

'label' => t('Separate text fields'),<br />

'description' => t(<br />

'Allow the user to enter each dimension separately.'),<br />

'field types' => array('dimensions'),<br />

'behaviors' => array(<br />

'multiple values' => FIELD_BEHAVIOR_DEFAULT,<br />

'default value' => FIELD_BEHAVIOR_DEFAULT,<br />

),<br />

),<br />

'dimfield_combined' => array(<br />

'label' => t('Combined text field'),<br />

'description' => t(<br />

'Allow the user to enter all dimensions together.'),<br />

'field types' => array('dimensions'),<br />

'settings' => array('size' => 10),<br />

[ 191 ]

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

Saved successfully!

Ooh no, something went wrong!