Score:0

How to render fields with ->view() in a render array table?

jo flag

I am building a table in my build function of a block and want to render formatted field values or entities with the ->view(); method in a cell of my table.

As described here: https://www.computerminds.co.uk/articles/rendering-drupal-9-fields-right-way

I have a value like this:

$cell_value = $entity->field_name->view();

It outputs a render array. But when I put it in the table like this. Nothing shows up.

  $header = [
      'col1' => t('COL1'),
      'col2' => t('COL2'),
    ];
    $rows = [
      ['test col 1', $cell_value],
      ['test col 1', 'test'],
      ['test col 1', 'test'],
    ];
    return [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];
  }

But when I render it like this:

return $cell_value;

I see a rendered value. Is there a way to render it in a table and how? Currently I am making every field manually which is very time consuming.

Kevin avatar
in flag
Why not make a table field formatter or theme the host entity with a view mode?
Jaypan avatar
de flag
At a glance I think you should have `['test col 1' => $cell_value],` and do the same for the other cells.
Score:2
cn flag

Usually it helps to put the render array in a data subkey:

$rows = [
  ['test col 1', ['data' => $cell_value]],
  ...
Michiel avatar
jo flag
Wow! thanks it works, so happy! Had to finish something soon, this saves me allot precious time and headache.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.