This blog post kicks off a series of posts where I am gonna quickly and tersely write about small-small problems we faced working with various platforms and provide quick solutions to them.

As for this blog-post, we recently had a scenario where we needed to add a row-specific css class to each row of a Drupal table. Here’s how we did it:

//Assuming $users contains the list of users to be rendered as a table.

$rows = [];
foreach ($users as $user) {	
	$row = array(
		'uid' => $user->uid,
		'name' => $user->name,
	);
	
	$rows[] = [
		'data' => $row,
		'class' => ['user-row-' . $row->uid],
	];
}

$header = array(
	array('data' => t('Id')),
	array('data' => t('Name')),
);

$build['table'] = array(
	'#theme' => 'table',
	'#header' => $header,
	'#rows' => $rows,
);

The line of interest is line number 12. Instead of directly appending the $row to the $rows array, we added it under data key, and specified the class as another key.

class itself is an array, so you can add as many classes (row specific or common across rows) as you need.

So that’s it. You have a Drupal table with a row specific css class added to each row.