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

}<br />

}<br />

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

'#title' => t('How many dimensions'),<br />

'#options' => array(<br />

2 => t('Height and width'),<br />

3 => t('Height, width, and depth'),<br />

),<br />

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

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

'#description' => t(<br />

'Is this for a 2-dimensional or 3-dimensional object?'),<br />

);<br />

return $form;<br />

We only have a single form element here, that is, a select box that lets the user select<br />

whether we're dealing with a 2-dimensional or 3-dimensional object. It is this value<br />

that will determine the structure of the field itself, as defined in the schema callback.<br />

Field validation<br />

Although there are a couple of other callbacks we could implement, there's only one<br />

that we will cover for now, as it is rather important, namely, validation.<br />

function dimfield_field_validate($obj_type, $object, $field,<br />

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

&$errors) {<br />

if ($field['type'] == 'dimensions')'' {<br />

$columns = array(<br />

'height' => 'max_height',<br />

'width' => 'max_width',<br />

);<br />

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

$columns['depth'] = 'max_depth';<br />

}<br />

foreach ($items as $delta => $item) {<br />

foreach ($columns as $column => $max_key) {<br />

if ($instance['settings'][$max_key] &&<br />

!empty($item[$column]) &&<br />

$item[$column] > $instance['settings'][$max_key]) {<br />

$errors[$field['field_name']][$delta][] = array(<br />

'error' => 'dimfield_' . $max_key,<br />

'message' => t(<br />

'%name: The %column may not be larger than %max.',<br />

array('%column' => $column,<br />

'%name' => $instance['label'],<br />

[ 189 ]

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

Saved successfully!

Ooh no, something went wrong!