0

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.

2
  • Why not make a table field formatter or theme the host entity with a view mode?
    – Kevin
    Jan 10, 2023 at 13:57
  • At a glance I think you should have ['test col 1' => $cell_value], and do the same for the other cells.
    – Jaypan
    Jan 10, 2023 at 14:27

1 Answer 1

2

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

$rows = [
  ['test col 1', ['data' => $cell_value]],
  ...
1
  • Wow! thanks it works, so happy! Had to finish something soon, this saves me allot precious time and headache.
    – Michiel
    Jan 10, 2023 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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