2

I need to create a table that will have a header with 4 columns and then all the rows will have 5 columns, so I need to add a colspan in the header.

This is an example of what I trying to do:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];

This code just give something like this:

enter image description here

But I trying to obtain something like this:

enter image description here

I tried the last example in Add a class to a Drupal table cell containing ['data'] but just give some errors.

If you go to see the class Table you will see an example using the colspan in the '#wrapper_attributes' but it seems not works for the '#header'

I can obtain a similar output just adding an empty header column like this:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  $this->t('Weight'),
  '',
  $this->t('Package'),
];

This will give something like this:

enter image description here

But I think that the correct way is adding the colspan property to the header.

Maybe I'm missing something or we just need to wait for Multi level (multirow) header for table FAPI element to use the colspan in the table header?

  • I found one way to solve this, but I wonder if there is another different way without using the preprocess hooks. – Adrian Cid Almaguer Sep 13 '17 at 13:07
4

I just found the solution looking a bit in the Multi level (multirow) header for table FAPI element and doing some test.

This is the way that I found:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  [
    'data' => $this->t('Weight'),
    'colspan' => 2,
  ],
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];
| improve this answer | |

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.