0

I am struggling to add multiple links to the same table cell, my current code looks like:

use Drupal\Core\Link;

$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$rows[] = ['data' => $row, 'no_striping' => TRUE];

return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $rows,
];

I've cut down the code to the relevant parts each element of the $row variable is a new cell and each element of the $rows variable is a new row. I need to use the data attribute as I have additional attributes on the cell.

At present this works perfectly fine, but my links are rendered in separate cells and I would like them rendered in the same cell. If I just to concatenate the 2 Link::createFromRoute I get the following error:

Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string

I've tried using the toString() and the toRenderable() functions and neither work as I want. Surely it can't be that hard?

  • 1
    I’m pretty sure you should only add one cell to the row, and make its data a render array containing the two links – Clive Jan 19 '18 at 12:35
2

I think you can do it as Clive alluded to with render array:

  $link_1 = Link::createFromRoute('Link 1', 'route_1')->toString();
  $link_2 = Link::createFromRoute('Link 2', 'route_2')->toString();
  $link_concat = ['#markup' => $link_1 . ' - ' . $link_2];

  $header = [ ... ];
  $row = [];
  $row[] = [
    'data' => \Drupal::service('renderer')->render($link_concat),
    'class' => 'middle',
  ];
return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $row,
];

This is just one method of doing it, there are a lot of ways you could potentially work this scenario. This way just puts the two links with a dash in between. But hopefully this will help guide you towards a solution.

  • This works, I tried ->toString() but didn't then add them to a #markup render array – Colin Shipton Jan 24 '18 at 15:13

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.