Create a sortable table using “theme_table()” function in Drupal

Sortable table using theme_table() function

Sortable table using theme_table() function


We can create a sortable header using “theme_table()” function. In sortable header user can sort a column in ascending or descending order. I am using a table called “package_coupon“. This table have seven fields (coupon, operator, operand, created, expire, used and user_by). We are providing the sorting facility on four fields only (coupon, created, expire and used). Initially, the coupon field is sorted by ascending order.

Here “tablesort_sql()” function is important. This function produces the ORDER BY clause to insert in your SQL queries, assuring that the returned database table rows match the sort order chosen by the user.

Code:-

function package_coupon_list() {
	$head = array(
		array('data' => t('Coupon'), 'field' => 'coupon', 'sort' => 'asc'),
		array('data' => t('Type of Discount')),
		array('data' => t('Created'), 'field' => 'created'),
		array('data' => t('Expire'), 'field' => 'expire'),
		array('data' => t('Status'), 'field' => 'used'),
		array('data' => t('Used by')),
	);
 
  	$sql = "SELECT * FROM package_coupon" . tablesort_sql($head);
 
   	$result = db_query($sql);
 
  	while ($coupon = db_fetch_object($result)) {
		$rows[] = array(
			array('data' => _coupon_format($coupon->coupon)),
			array('data' => ($coupon->operator == '%' ? "{$coupon->operand}% discount" : "\${$coupon->operator}{$coupon->operand} discount")),
			array('data' => format_date($coupon->created, 'small')),
			array('data' => format_date($coupon->expire, 'small')),
			array('data' => $coupon->used . ' left'),
			array('data' => ($coupon->user_by == '') ? 'None' : $coupon->user_by),
		);
  	}
 
	return theme_table($head, $rows);
}


  1. #1 by Tanmoy Saha - June 16th, 2009 at 16:10

    Excellent one !!!

  2. #2 by Shogikishi - June 26th, 2009 at 04:21

    I think you have a definite skill for communication. I read a lot of articles on how to use theme_table() over the last week and yours was the most clear and understandable. After seeing the code you used and the final product, I was able to implement it in just a few minutes, then spend the rest of my time expanding on it to get the functionality I needed. Thank you so very much for taking the time to explain it!

  3. #3 by admin - June 26th, 2009 at 10:25

    @ Shogikishi
    Thanks.

  4. #4 by litwol - June 27th, 2009 at 15:21

    theme_table(…) should be theme(‘table’, $head, $rows);

    by using theme(‘table’, $head, $rows); instead of theme_table you allow yourself to use theme function overrides much easier.

  5. #5 by Matt - August 25th, 2009 at 21:19

    Thank you! This is so cool and saves so much time.

  6. #6 by Mohit - June 2nd, 2010 at 17:01

    Thanks for
    superb Solution ;-)

(will not be published)


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.