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.

Chapter 7<br />

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

$form['size'] = array(<br />

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

'#title' => t('Size of textfield'),<br />

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

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

'#element_validate' =><br />

array('_element_validate_integer_positive'),<br />

);<br />

}<br />

}<br />

return $form;<br />

As with all of our other callbacks, we check the widget type and then return a form<br />

fragment for the field we want. Note that the textfield is named the same as the<br />

setting property we defined in dimfield_field_widget_info(), which is how<br />

<strong>Drupal</strong> knows which setting is which. We also are leveraging the Form API's ability<br />

to provide element-specific validators. In this case, we are using a validation callback<br />

that <strong>Drupal</strong> provides. It will throw a validation error if the user specifies anything<br />

other than a positive integer. (A widget size of -7.4 would not make much sense,<br />

would it?)<br />

Now, we can expand our field_widget_form callback to include our new widget.<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 />

// ...<br />

}<br />

elseif ($instance['widget']['type'] == 'dimfield_combined') {<br />

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

'_dimfield_combined_validate');<br />

$default = NULL;<br />

if (isset($items[$delta])) {<br />

$item = $items[$delta];<br />

if (isset($item['height'], $item['width'])) {<br />

$default = $item['height'] . 'x' . $item['width'];<br />

if ($field['settings']['num_dimensions'] == 3) {<br />

$default .= 'x' . $item['depth'];<br />

}<br />

[ 195 ]

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

Saved successfully!

Ooh no, something went wrong!