Add extra pseudo aka "dummy" fields to nodes and any entity

Public

We want to add a field to a node that's not in db but should be available on a node display and draggable on node display edit screen.

Get raw version
php
  1. /**
  2. * Implements hook_field_extra_fields().
  3. */
  4. function MODULE_NAME_field_extra_fields() {
  5. $field_name = 'my_extra_field';
  6. $node_type = 'article';
  7. $extra['node'][$node_type]['display'][$field_name] = array(
  8. 'label' => t('Field title'),
  9. 'description' => t('Field description.'),
  10. // default weight value
  11. 'weight' => 50,
  12. );
  13. return $extra;
  14. }
Get raw version
php
  1. /**
  2. * Implements hook_node_view().
  3. * For other entity types you can use hook_entity_view().
  4. */
  5. function MODULE_NAME_node_view($node, $view_mode, $langcode) {
  6. $extra_fields = field_info_extra_fields('node', $node->type, 'display');
  7. $field_name = 'my_extra_field';
  8. if (!empty($extra_fields[$field_name]['display'][$view_mode]['visible'])) {
  9. // Your extra field logic goes here. It can be any renderable array.
  10. $node->content[$field_name] = array(
  11. '#type' => 'item',
  12. '#markup' => t('Hello world!'),
  13. );
  14. }
  15. }