3

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?

1
  • I found one way to solve this, but I wonder if there is another different way without using the preprocess hooks. Commented Sep 13, 2017 at 13:07

1 Answer 1

6

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,
];

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.