[Drupal] How to display items in table listings with checkboxes on each row, on a Drupal 7 site?

| | 2 min read

This is a description of how you can display table listings with checkboxes on each row on a Drupal site. The requirement in one of my projects was that "Admin can select multiple checkboxes against the details of a user, and can run an update query when update button is clicked."
To implement this, I made use of Drupal 7's table_select() function which saved my time and made my code less complicated. Now, if you want to know how you can make use of this functionality in one of your projects, you may read on.

Using an example to illustrate - Consider the following table:

First Name Last Name
1 Nidhi sen
2 Smruthy Jyothish


To build a table like above, use the following steps:

Step 1: Define the format of the data.

$users = array(
  array('uid' => 1, 'first_name' => 'Nidhi', 'last_name' => 'sen'),
  array('uid' => 2, 'first_name' => 'Smruthy', 'last_name' => 'Jyothish'),
);

The basic thing about tableselect element is that, it depends on the keys to match columns of appropriate header. So, obviously the next step is to define the header and options.

Step 2: The header for the above table can be defined as:

$header = array(
  'first_name' => t('First Name'),
  'last_name' => t('Last Name'),
);

Step 3 : Build the data

In this step, you have to build the options array that will hold the values of table. In the light of above table,

$options = array();
foreach ($users as $user) {
  $options[$user['uid']] = array(
    'first_name' => $user['first_name'], // 'first_name' was the key used in the header
    'last_name' => $user['last_name'], // 'last_Name' was the key used in the header
  );
} 

Step 4: Integration of data

Now to bring the above header and options together,
a) create a form element with type 'tableselect', '#header' with value $header and '#options' with value $options.

$form['table'] = array (
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
);

You need not worry about creating/calling a theme function, because the render element 'tableselect', calls the theme function theme_tableselect(), which takes the data, converts it into a table, adds a check-box to each row and adds a 'select-all' check-box to the header.

This should give you a headstart on your theming requirement. Do let me know if you have any doubts regarding this using the Comments box below.

Happy Coding!

References:

1. http://www.jaypan.com/tutorial/themeing-drupal-7-forms-tables-checkboxe…