Drupal is very cooperative when it comes to displaying html tables. There are functions for creating and theming the tables. For one of my projects my requirement was to add checkboxes for every rows in the table and also a select all checkbox at the top. The user can select more than one checkboxes or all of them and when he hits the submit button then those records will be deleted.
For this I had to create a form and create the table inside the form and add type of table as "tableselect". Here is the code which created the table with the checkboxes.
function cpanel_showtime_table_form($form, $form_state)
{
$header = array('Sl#', 'Movie', 'Cinema Hall', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday','Wednesday','Thursday');
$rows = array();
$attributes = array('width = "100%" ');
$no_yes = array('No', 'Yes');
$results = db_query("SELECT cst.*,nd.title as movie,ttd.name as cinema_hall
FROM custom_show_time cst LEFT JOIN {node} nd ON cst.movie_id = nd.nid
LEFT JOIN {taxonomy_term_data} ttd ON cst.cinemahall_id = ttd.tid
WHERE nd.type = 'movies'
ORDER BY nd.title ");
$counter = 1;
foreach ($results as $result)
{
$rows[$result->id] = array(
$counter,
$result->movie,
$result->cinema_hall,
str_ireplace('|',',','['.$result->friday_date.']<br>'.$result->friday),
str_ireplace('|',',','['.$result->saturday_date.']<br>'.$result->saturday),
str_ireplace('|',',','['.$result->sunday_date.']<br>'.$result->sunday),
str_ireplace('|',',','['.$result->monday_date.']<br>'.$result->monday),
str_ireplace('|',',','['.$result->tuesday_date.']<br>'.$result->tuesday),
str_ireplace('|',',','['.$result->wednesday_date.']<br>'.$result->wednesday),
str_ireplace('|',',','['.$result->thursday_date.']<br>'.$result->thursday),
);
$counter++;
}
$table = array('header' => $header, 'rows' => $rows, 'attributes' => $attributes, 'sticky' => FALSE);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Remove'),
);
$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#empty' => t('No records found'),
);
return $form;
}
When you create the html table with the drupal type "tableselect", then it automatically creates checkboxes at the front of each row as well as a "select all" checkbox at the top. The values of each individual checkbox is the key of the $rows array i.e. "$result->id".
Thus when the form is submitted you can capture the values and delete like this:
function cpanel_showtime_table_form_submit($form, &$form_state)
{
foreach($form_state['values']['table'] as $item)
{
if($item != 0)
{
$num_deleted = db_delete('custom_show_time')
->condition('id', $item)
->execute();
}
}
drupal_set_message('Records Deleted');
}