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

Since measurements of length do not really make sense without a unit, we will also<br />

record what unit the dimensions are in, such as inches or meters. To keep things<br />

simple we will only save integers, although in practice we would want to support<br />

float values. Also note that the whole function is wrapped in an if() statement to<br />

check for the field type. If we were defining multiple field types in this module, they<br />

would define their schema using the same function and we'd have to differentiate<br />

between them based on the value of $field['type'].<br />

Defining empty<br />

The second magic callback we need is to determine if a given field has an empty<br />

value. While that may seem like a simple question, it is actually dependent on our<br />

particular application.<br />

Consider this: Is a dimension field empty if it has no height but only has a width, or<br />

only if both values are empty? <strong>Drupal</strong> doesn't know which we mean, so we need to<br />

tell it.<br />

function dimfield_field_is_empty($item, $field) {<br />

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

if (empty($item['height']) && empty($item['width']) &&<br />

($field['settings']['num_dimensions'] == 2 ||<br />

empty($item['depth'])))<br />

{<br />

return TRUE;<br />

}<br />

}<br />

return FALSE;<br />

}<br />

In the preceding snippet, we define empty to mean that all dimensions in use are an<br />

empty value, which PHP defines to include an empty string or 0. Again note that we<br />

are checking against the specific field type since we could add another field type to<br />

this module later.<br />

Field settings<br />

Although not absolutely required, we also need a configuration form for the field<br />

settings. Most fields will be configured through <strong>Drupal</strong>'s web interface, so we need a<br />

form to allow users to set the available options. That's another magic callback. Let's<br />

look at an example:<br />

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

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

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

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

[ 188 ]

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

Saved successfully!

Ooh no, something went wrong!