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.

Creating New Fields<br />

}<br />

'behaviors' => array(<br />

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

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

),<br />

),<br />

);<br />

In the preceding snippet, we are defining two widgets rather than just one. The first<br />

is a simple widget, consisting of simple text fields, one for each dimension. In the<br />

second, we offer only a single text field into which the user will enter all two or<br />

three dimensions in H×W×D format.<br />

Both widgets explicitly specify the field types that they will work on. Although<br />

we are defining these widgets in the same module as the field type, that doesn't<br />

necessarily imply a relationship between them. In fact, any module may define<br />

widgets that work with any field type. The widget just needs to know how that field<br />

type wants its data. The second widget also includes a settings array, which allows<br />

us to configure the widget per-instance.<br />

Also note the behaviors property. By default, widgets will handle only a single<br />

field value and <strong>Drupal</strong> itself will offer a dynamic way to add additional values<br />

from within the form. However, we can also tell <strong>Drupal</strong> to let our widget handle<br />

multi-value fields in case, for example, we want to offer a clickable map for<br />

multi-value coordinates we discussed earlier.<br />

Simple widget forms<br />

Let's look at the simple widget first, and then come back and look at the more<br />

complex one. The only callback we must define for a widget is its form callback,<br />

which defines the form fields that make up the widget. Let's look at an example:<br />

function dimfield_field_widget_form(&$form, &$form_state, $field,<br />

$instance, $langcode, $items,<br />

$delta, $element) {<br />

$base = $element;<br />

if ($instance['widget']['type'] == 'dimfield_simple') {<br />

$element['height'] = array(<br />

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

'#title' => t('Height'),<br />

'#default_value' => isset($items[$delta]['height']) ?<br />

$items[$delta]['height'] : NULL,<br />

) + $base;<br />

[ 192 ]

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

Saved successfully!

Ooh no, something went wrong!