How to create a pseudo-field(field extras) in Drupal

An extra field allows you to create a managed field with custom content.

First of all we need to define our extra field.

/**
 * Implements hook_entity_extra_field_info().
 */
function hook_entity_extra_field_info() {
  $extra = [];

  $extra['node']['MY_NODE_TYPE']['display']['MY_CUSTOM_FIELD_KEY'] = [
    'label' => t('My pseudo field'),
    'description' => t('My pseudo field description.'),
    'weight' => 0,
    'visible' => TRUE,
  ];

  return $extra;
}

Then just populate some value on hook_node_view()

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('MY_CUSTOM_FIELD_KEY')) {
    $build['MY_CUSTOM_FIELD_KEY'] = [
      '#markup' => 'This is my custom content',
    ];
  }
}

Drupal 7 example

/**
 ** Implements hook_field_extra_fields().
 **/
function hook_field_extra_fields() {
  $extra['node']['MY_NODE_TYPE']['display']['MY_CUSTOM_FIELD_KEY'] = array(
    'label' => t('My pseudo field'),
    'description' => t('My pseudo field description.'),
    'weight' => 0,
  );
  return $extra;
}

/**
 ** Implements hook_node_view().
 **/
function hook_node_view($node, $view_mode, $langcode) {
  // Get all extra fields for current node.
  $extra_fields = field_info_extra_fields('node', $node->type, 'display');
  // Managed by display mode configuration.
  if (!empty($extra_fields['MY_CUSTOM_FIELD_KEY']['display'][$view_mode]['visible'])) {
    $node->content['MY_CUSTOM_FIELD_KEY'] = array(
      '#markup' => 'This is my custom content',
    );
  }
}

 

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************