2

I'm building a table with TableSort retrieved by EntityQuery like explained in this post.

The result fields vary a lot and I have a hard time to figure out how to render the results of the different field types, like dates, arrays of entities, taxnomomies, etc.

The most simple way to format the rows is just outputting the field values:

$row = [
    'data' => [
        $node->title->value,
        $node->field_date->value,
        $node->field_persons->value,
        $node->field_tags->value,
];

Now I want to output every column in a different way:

  • titles linked to the node
  • dates formatted and not as timestamps
  • persons as list with every person name linked to his node
  • tags as list with every tag linked to it's taxonomy

I managed to get titles and dates outputted like I wanted, but I can't figure out to do that for persons and tags:

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\NODE::load($nid);
    $link['#markup'] = '<a href="/node/'.$nid.'">'.$node->title->value.'<a>';

    kint($node);

    $row = [
        'data' => [
            \Drupal::service('renderer')->render($link),
            format_date((int)$node->field_date->value,'custom','Y-m-d'),
            $node->field_persons->value,
            $node->field_tags->value,
        ],
    ];
    $rows[] = $row;
}

Is there a more elegant way to output content of individual fields? Or do I have to find out for every field how to output it investigating it's field type and building the result on my own?

How would I do that for persons or tags outputting the list of result with links to their nodes?

5

Fields have a view() method that accept either a view mode or an array with formatter/display settings (same format as stored in a view display config entity or passed to a base field).

$entity->get('field_date')->view('teaser').

That returns a render array that you can then display.

If you also use #type table then you can make each row a numeric child key and you can directly use the render array.

2
  • Thanks to the view() method I displayed a person with $node->field_persons->view()[0]['#title']. I still can't figure out so how to use the formatter/display settings. Any documentation on that?
    – geraldo
    Nov 4 '18 at 14:43
  • Those settings are pretty arbitrary @geraldo, I think the plugin classes themselves are possibly going to be the best documentation
    – Clive
    Nov 4 '18 at 17:48

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.