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 />

}<br />

}<br />

$element['dimfield_combined_wrapper']['#theme'] =<br />

'dimfield_combined_wrapper';<br />

$element['dimfield_combined_wrapper']['height_width_depth'] =<br />

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

'#default_value' => $default,<br />

'#size' => $instance['widget']['settings']['size'],<br />

) + $base;<br />

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

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

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

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

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

'#options' => dimfield_units(),<br />

);<br />

}<br />

return $element;<br />

In the first block of code, we assemble our default value for the form element out of<br />

the values available in the field. Since our widget is only handling a single instance,<br />

we have to check for just this one delta to see if we have a value defined. If so, we<br />

concatenate the height, width, and potential depth together with an × between them.<br />

Then we set up our two form elements. One is our combined height, width, and<br />

depth text field and the other is the units, as we've seen before. The most important<br />

part, however, is that very first line:<br />

$element['#element_validate'] = array('_dimfield_combined_validate');<br />

Just as we specified an existing validation callback for a text field a moment ago, this<br />

time we will specify a custom validation callback. However, we won't be using it just<br />

for validation. Rather, we will be using it to modify the submitted form values. Let's<br />

have a look at that function given here:<br />

function _dimfield_combined_validate($element, &$form_state) {<br />

// This function is also called when submitting the field<br />

// configuration form. If so, skip validation as it<br />

// won't work anyway.<br />

if ($form_state['complete form']['#form_id'] ==<br />

[ 196 ]

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

Saved successfully!

Ooh no, something went wrong!