15 Sep 2013 16:33:40
Implement custom field formatter
Drupal formatters provide field value representation as renderable array, it can be configured via content type (or some another fieldable entity_type) display settings interface. I.e. you can choose different formatters for each field of certain entity view_mode & transfer settings via features module to another instance.To provide formatter you need:
- 1. Implement hook_field_formatter_info (it's just a list of available formatters for certain field types).
- 2. Implement hook_field_formatter_view (it's callback where field renderable array for drupal_render will be assembled).
- 3. Config your view modes settings & set new implemented formatters for needed fields.
/** * Implements hook_field_formatter_info(). */ function pavelruban_field_formatter_info() { return array( 'pavelruban_text_formatter' => array( 'label' => t('My formatter'), // For what field types this formatter will be available. 'field types' => array( 'text', 'text_long', 'text_with_summary', 'commerce_price', 'addressfield', 'date', 'datetime', 'datestamp', 'list_integer', ), ), ); }
/** * Implements hook_field_formatter_view(). */ function pavelruban_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) { $element = array(); $settings = $display['settings']; // This is formatter machine name, this callback is executed // for all module's specified formatters. switch ($display['type']) { case 'pavelruban_text_formatter': if (!empty($items)) { foreach ($items as $delta => $item) { // Here you can build render array manually // or used already implemented. $element[$delta] = array( '#type' => 'pavelruban_type', '#field_value' => $itemp['value'], '#label' => !empty($instance['label']) ? $instance['label'] : '', ); } } } break; } return $element; }