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

Formatters follow a very similar pattern to field types and widgets. There is an<br />

info hook to define what formatters are available, and then there's a series of<br />

callbacks for all of the formatters our module defines. In most cases though,<br />

there's only one callback we need worry about.<br />

Declaring a formatter<br />

First, let's look at the info hook given here:<br />

function dimfield_field_formatter_info() {<br />

return array(<br />

'dimfield_default' => array(<br />

'label' => t('Default'),<br />

'field types' => array('dimensions'),<br />

),<br />

'dimfield_table' => array(<br />

'label' => t('Show as table'),<br />

'field types' => array('dimensions'),<br />

'settings’ => array('units_as' => 'column'),<br />

),<br />

);<br />

}<br />

In the preceding snippet we define two formatters, and there's not much to define.<br />

Each formatter has an internal name defined by the array key, a human-readable<br />

label, and a list of the field types that it applies to. Just as with widgets, we can define<br />

a formatter in any module that works with any field type we want, as long as we<br />

know how to handle the data it gives us.<br />

Single-value formatters<br />

Formatters only have two callbacks, and most formatters will only use one. Again,<br />

let's look at the simple implementation first.<br />

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

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

$display) {<br />

$element = array();<br />

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

switch ($display['type']) {<br />

case 'dimfield_default':<br />

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

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

$output = t('@height @unit by @width @unit', array(<br />

[ 200 ]

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

Saved successfully!

Ooh no, something went wrong!