Drupal 7 create a sortable table with pager

Recently I was working on the core php website and after using drupal creating website in core php is really tough challenge as we are use to most of the inbuilt functionality.  Drupal take cares user registration and login, user acess based on roles. Creating menus, formatting html etc. Drupal is really powerful CMS. Drupal hooks and apis are just awesome. Don't have to hack any core files and we can update the drupal CMS easily.


Yesterday I have to create a table for the core PHP website with pagination and sort able columns and i was doing this for more than 5 hours. Just adding different types of mysql queries depend on $_GET parameters calculating pagers and its first, next, last values. Then i thought how to add table with pagination in Drupal ?? Adding sorting functionality to drupal table is that much difficult ?
So gone through some Drupal Module Development Reference Books and i was shocked by the code. There is nothing to do in it just few lines of code and special thanks to drupal api theme()Its all easy. Here is a small example from node module.
Lets start with simple hook_menu to create a custom page.
 *  Implements hook_menu()
function MYMODULE_menu() {
  $items['drupal7-table-demo'] = array(
    'title' => 'Drupal 7 Table Demo',
    'page callback' => 'table_demo',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  return $items; 
Here is the page callback function which has all the magic part of creating table in drupal 7.
function table_demo() {
  $header = array(
    'title' => array('data' => t('Title'), 'field' => 'n.title'),
    'type' => array('data' => t('Type'), 'field' => 'n.type'),
    'author' => t('Author'),
    'status' => array('data' => t('Status'), 'field' => 'n.status'),
    'changed' => array('data' => t('Updated'), 'field' => 'n.changed', 'sort' => 'desc')
  $query = db_select('node', 'n')->extend('PagerDefault')->extend('TableSort');
  $nids = $query
  $nodes = node_load_multiple($nids);
  foreach ($nodes as $node) {
    $options[$node->nid] = array(
      'title' => $node->title,
      'type' => check_plain(node_type_get_name($node)),
      'author' => theme('username', array('account' => $node)),
      'status' => $node->status ? t('published') : t('not published'),
      'changed' => format_date($node->changed, 'short'),
  $output = theme('table', array('header' => $header, 'rows' => $options));
  $output .= theme('pager');
  return $output;



I just like the helpful information you provide on your articles.

I'll bookmark your blog and take a look at again here frequently.
I'm relatively certain I will be informed lots of new stuff right right here!

Best of luck for tthe next!

I needed to thank you for this great read!!
I absolutely enjoyed every bit of it. I have you book-marked to look at new things
you post…