How to manually sort table in Drupal

Drupal provides powerful and flexible built-in table sort functionality. However, it will only work with database query through standard db_query() and pager_query(). In many cases, rows are fetched from external system, e.g., mailbox. We may add a few lines to get the same behavior.

You still need to prepare $headers like normal table.

  $form['header'] = array('#type' => 'value', '#value' => array(
    theme('table_select_header_cell'),
    array('data' => t('ID'),'field' => 'sid'),
    array('data' => t('Title'),'field' => 'title'),
    array('data' => t('Status'),'field' => 'status', 'sort' => 'asc'),
  ));

For $rows, it is just an array of array. The internal arrays are associate array where keys match above field.

  $ts = tablesort_init($headers);
  if ($ts['sql']) {
    $rows = btqueue_column_sort($rows,$ts['sql']);
    if ($ts['sort'] == 'desc') {
      $rows = array_reverse($rows);
    }
  }

Tags: , ,

Reply