In Drupal 8, rendering Tables is still a lot like Drupal 7. You build out multi-dimensional arrays of rows and columns in PHP that Drupal transforms into a <tr>
and <td>
s respectively. There is still this confusing Drupalism known as 'data'
that lets you add render array elements as cell data (not to be confused with data attributes).
I've been given a site where the developer chose to use 'data' to render the contents of the cell, but I cannot figure out how to add a class to the <td>
around the data.
I've read the source code and documentation for Table.php and I'm aware of the new #wrapper_attributes
but I cannot crack this.
I've tried at least four ways to add the class, and none work.
$table['row-' . $row_id] = [
// Option 1: Class appears on <tr> tag
'#attributes' => [
'class' => ['option-1-row-attributes'],
'id' => 'row-' . $row_id,
'no_striping' => TRUE,
],
// Option 2: Class appears on <td> tag of first column.
'item' => [
'#markup' => $row['my_item']->label(),
'#wrapper_attributes' => [
'class' => ['option-2-markup-wrapper-attributes'],
],
],
// In the following section, the only item that works is
// the class on the <a> tag.
'edit_operation' => [
'data' => [
'#type' => 'link',
'#url' => Url::fromRoute('my_module.my_route', ['item' => $row_id]),
'#title' => $this->t('Edit'),
'#attributes' => [
// Option 3: Class appears on the anchor tag
'class' => ['use-ajax', 'option-3-link-attributes'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
// Option 4: Has no effect.
'#wrapper_attributes' => [
'class' => ['option-4-data-wrapper-attributes'],
],
],
// Option 5: Update: This appears to be the correct solution!
// Class appears on the <td>.
'#wrapper_attributes' => [
'class' => ['option-5-wrapper-attributes'],
],
// Option 6: Has no effect.
'#attributes' => [
'class' => ['option-6-attributes'],
],
// Option 7: Has no effect.
'class' => ['option-7-attributes'],
],
];