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.

Creating New Fields<br />

In this simple case, all we're doing is creating two or three form elements for the<br />

dimensions, one for each dimension, and a select box to set the units. The available<br />

units are provided by a simple utility function that we also write:<br />

function dimfield_units($unit = NULL) {<br />

static $units;<br />

if (empty($units)) {<br />

$units = array(<br />

'inches' => t('Inches'),<br />

'feet' => t('Feet'),<br />

'meters' => t('Meters'),<br />

);<br />

}<br />

if ($unit) {<br />

return isset($units[$unit]) ? $units[$unit] : '';<br />

}<br />

}<br />

return $units;<br />

That little utility function lets us get a consistent list of units we support anywhere<br />

we need it, plus it provides an easy mapping from the "internal name" of a unit to a<br />

translated human-friendly name.<br />

It is important to note that the form elements we're creating are named exactly the<br />

same as the columns of the dimensions field. <strong>Drupal</strong> needs the "processed form" value<br />

to have the exact same "form element" names as the field columns so that it can save<br />

them properly. What makes this a simple widget is that the form maps one-to-one to<br />

the field definition, so we don't need to do any extra processing. At this point, we are<br />

in essence done. Users will be able to select our widget, <strong>Drupal</strong> will handle the multivalue<br />

logic for us, and save the data to the field, all without further interaction from us.<br />

Complex widgets<br />

Let's now look at the more complex widget. In this case, we will show all dimensions<br />

together in a single text field so that the user need only fill in a single field.<br />

First off, because our more complex widget has settings that we need to implement,<br />

we use the widget_settings_form callback, given as follows:<br />

function dimfield_field_widget_settings_form($field, $instance) {<br />

$form = array();<br />

$widget = $instance['widget'];<br />

$settings = $widget['settings'];<br />

[ 194 ]

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

Saved successfully!

Ooh no, something went wrong!