3 min read

Drupal Extra Fields: Integration with Views

Drupal’s field system provides a useful hook, hook_field_extra_fields, allowing you to add additional fields with custom logic to entities.

To define, add, and display such a field, the following example is sufficient:

/**
 * Implements hook_field_extra_fields().
 */
function amazing_extra_fields_field_extra_fields() {
  return array(
    'node' => array(
      'article' => array(
        'display' => array(
          'random_field' => array(
            'label' => t('Random field'),
            'description' => t('Random field'),
            'weight' => 0,
          ),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_node_view().
 */
function amazing_extra_fields_node_view($node, $view_mode, $langcode) {
  $extra_fields = field_extra_fields_get_display('node', $node->type, $view_mode);
  if (isset($extra_fields['random_field']) && $extra_fields['random_field']['visible']) {
    $node->content['random_field'] = array(
      '#markup' => amazing_extra_fields_random_field_content(),
    );
  }
}

/**
 * Random field content
 */
function amazing_extra_fields_random_field_content() {
  return rand();
}

After this, the field will appear in the content type’s display management settings.

Drupal 7 Extra Fields

Integration with Views

The first issue you might encounter with extra fields is their unavailability in Views when selecting “fields” as the view display type. To make extra fields available in Views, use the Extrafield Views Integration module.

Simply install and enable the module, then add a callback function for the field in your hook_field_extra_fields implementation. Here’s the complete field definition code:

/**
 * Implements hook_field_extra_fields().
 */
function amazing_extra_fields_field_extra_fields() {
  return array(
    'node' => array(
      'article' => array(
        'display' => array(
          'random_field' => array(
            'label' => t('Random field'),
            'description' => t('Random field'),
            'weight' => 0,
            'callback' => 'amazing_extra_fields_random_field_callback',
          ),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_node_view().
 */
function amazing_extra_fields_node_view($node, $view_mode, $langcode) {
  $extra_fields = field_extra_fields_get_display('node', $node->type, $view_mode);
  if (isset($extra_fields['random_field']) && $extra_fields['random_field']['visible']) {
    $node->content['random_field'] = array(
      '#markup' => amazing_extra_fields_random_field_content(),
    );
  }
}

/**
 * Random field callback (for views)
 */
function amazing_extra_fields_random_field_callback($node) {
  return amazing_extra_fields_random_field_content();
}

/**
 * Random field content
 */
function amazing_extra_fields_random_field_content() {
  return rand();
}

Now your additional field will be available in Views.

Drupal 7 Extra Fields