How to Work with Pseudo-Fields in Drupal 7

| | 2 min read

What are Pseudo-Fields?

Pseudo field is a field that you can add to any content entity type. For example, you can add a pseudo-field to nodes, taxonomy terms, users, paragraphs, etc. You can hide this field in the UI, but you cannot change it's value, because the content of this field is generated via the code.

How to Manage Pseudo Fields?

You're already familiar with the "Manage Fields" and "Manage Display" options provided in Structure > Content Types under the Drupal Admin part of a site. Manage Fields allows you to define Fields and order them by how they should appear in an edit or create form, while Manage Display allows you to order the fields per view mode, like Teaser or Full page view.

But you may have also noticed some non-editable fields appear in Manage Display such as the node title or URL redirects. Content editors can hide or show this field in display settings of the entity, but the value of this field can’t be changed from the user interface. This type of field is called ‘Pseudo Field’.

Scope of this Field

This is useful for modules that manage their own data attached to an entity or if you want to expose another modules property via Fields UI. These pseudo fields are typically used to expose entity properties that are not managed by "Manage Fields". So, by using pseudo fields, you get all the benefits that other fields created from the UI have, like drag and drop functionality to control visibility and position, but at the same time you can dynamically generate its content.

Pseudo field's value can be any renderable array, means that you can return whatever you want like view, form, block or even another entity.

Implementation

To attach a pseudo field, you need to implement only two hooks. The following is a simple example showing how to add an extra field to the Field UI and provides an example of one way of inserting the field onto a node.


/**
 * Implements hook_field_extra_fields().
 */
function example_field_extra_fields() {
  $extra['node']['article']['display']['field_extra_field'] = array(
    'label' => t('Pseudo field label'),
    'description' => t(‘Pseudo field description.'),
    'weight' => 0,
  );
  return $extra;
}

/**
 * Implements hook_node_view().
 */
function example_node_view($node, $view_mode, $langcode) {
  if ($view_mode === 'full' && $node->type === 'article') {
    $node->content['field_extra_field'] = array(
     '#markup' => '<p> This is inserted unless hidden in the field UI.</p>’,
    );
  }
}

Here I attached a pseudo field named 'field_extra_field' to the Article entity and you can test this easily. Just paste the code in your .module file, flush all caches and go to the following page: "admin/structure/types/manage/article/display" where you can see your new field.