You are here

function field_example_field_formatter_view in Examples for Developers 7

Implements hook_field_formatter_view().

Two formatters are implemented.

  • field_example_simple_text just outputs markup indicating the color that was entered and uses an inline style to set the text color to that value.
  • field_example_color_background does the same but also changes the background color of div.region-content.

See also

field_example_field_formatter_info()

Related topics

File

field_example/field_example.module, line 139
An example field using the Field Types API.

Code

function field_example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {

    // This formatter simply outputs the field as text and with a color.
    case 'field_example_simple_text':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          // We create a render array to produce the desired markup,
          // "<p style="color: #hexcolor">The color code ... #hexcolor</p>".
          // See theme_html_tag().
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#attributes' => array(
            'style' => 'color: ' . $item['rgb'],
          ),
          '#value' => t('The color code in this field is @code', array(
            '@code' => $item['rgb'],
          )),
        );
      }
      break;

    // This formatter adds css to the page changing the '.region-content' area's
    // background color. If there are many fields, the last one will win.
    case 'field_example_color_background':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#value' => t('The content area color has been changed to @code', array(
            '@code' => $item['rgb'],
          )),
          '#attached' => array(
            'css' => array(
              array(
                'data' => 'div.region-content { background-color:' . $item['rgb'] . ';}',
                'type' => 'inline',
              ),
            ),
          ),
        );
      }
      break;
  }
  return $element;
}