1

Usecase: I want to have a title field in view mode administration to be able to place it between some other fields. This field has different content depending on node type, view mode and some other fields which is handled by a custom function.

Solution so far:

 /**
 * Implements hook_entity_extra_field_info().
 */
function mymodule_entity_extra_field_info() {
  $extra = array();

  foreach (NodeType::loadMultiple() as $bundle) {
    $extra['node'][$bundle->Id()]['display']['mymdoule_title'] = array(
      'label' => t('Extra title'),
      'description' => t('Display the title of the node e.g. in teaser'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}

And then

/**
 * Implements hook_ENTITY_TYPE_view for nodes
 *
 *  - render our pseudo fields
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  // if our pseudo field is used we use our costum class to build the render array
  if ($display->getComponent('mymodule_title')) {
    $nodeCustomisation = new NodeCustomisation($entity);
    $nodeCustomisation->titleExtraField($build, $view_mode);
  }
}

It is working as I can see my pseudo field when I go to the view mode administration page of any content type. I can place the field somewhere and it is rendered.

Problem: As soon as the pseudo field is the only field with content when viewing a node in this view mode nothing is rendered but the node wrapping <article>-tag from node.html.twig. The array {{ content }} in this twig template is empty although the pseudo field should have content for sure - when I add a node field to the view mode which has content I see my pseudo field again.

1

So I found my fault - when you describe a field the render array needs to have an array of field items. So the $build-array needs to look like this:

$build['igb_title'][] = array(
      '#type' => 'html_tag',
      '#tag' => 'h2,
      '#value' => $entity->label()
    );

In field_group_remove_empty_display_groups it is checked if a field as at least one item:

$has_items = isset($element[$name][0]);

If $has_items is false the field group is emptied if there is no other field with a value. I think I might need to go deeper into this render array thing...

Best, Tobias

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.