1

I have a table in a form such as the 'user_admin_account' form. In one of the TD's I want to add a class, how do I do this the most convenient way?

This is what I currently have, it doesn't seem to work

$row = array(
  'title' => array(
    'data' => array(
      '#title' => $name . ' ' . $surname,
      '#attributes' => array(
        'class' => array(
          'myClass',
        ),
      ),        
    ),
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

2 Answers 2

6

The variables for theme_table() are structured differently to a standard render array, so you need to format your array slightly differently:

$row = array(
  'title' => array(
    'data' => $name . ' ' . $surname,
    'class' => array('myClass')
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

The above produces:

<table>
  <tbody>
    <tr class="odd">
      <td class="myClass"> </td>
      <td>1970-01-01</td>
      <td> </td> 
    </tr>
  </tbody>
</table>

The first and last column are only empty as my test environment doesn't have the same variables defined as in your code.

1
  • This looks ok, but it means hardcoding field names. It makes the code depend on the fields and views configuration. Are you aware of any solution that allows to configure the column class in the UI ?
    – donquixote
    Commented Mar 1, 2016 at 4:41
1

The documentation for theme_table() describes what the function is expecting in $variables['rows'], and it says:

rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

  • "data": an array of cells
  • Any HTML attributes, such as "class", to apply to the table row.
  • "no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

The example present in that page is the following one:

$rows = array(
  // Simple row
    array('Cell 1', 'Cell 2', 'Cell 3'),
    // Row with attributes on the row and some of its cells.
    array(
      'data' => array('Cell 1', array('data' => 'Cell 2', 'colspan' => 2)), 'class' => array('funky'))
    );

In that example, "funky" is the CSS class applied to the second row, which contains two cells; the second cell takes the room of two cells (because the 'colspan' => 2 part).

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.