A Drupal 7 form table example

If you're interested in building an HTML table with Drupal, Drupal 7 in this case, here's a quick example of how this can be done.

My Drupal "theme table" approach currently provides the following functionality:

  • Simple listing of database information in an HTML table format.
  • Adding a hyperlink to the first field of each row to support editing.
  • Adding a "pager" to the table so users can scroll through the result set.

The only thing I want in this table that I currently don't have is the ability to sort each column. When I figure out how to do that, I'll add that here as well.

Currently my Drupal 7 table looks like this:

A Drupal 7 form table example (form, module example)

This example is shown with the default Drupal 7 admin theme.

Drupal form table source code

Here's my Drupal form/module source code that corresponds to that table:


require_once 'common.inc';

 * The "List Projects" table
 * ----------------------------------------------------------------------
function projects_list() {

  $header = array('Name', 'Type', 'Updated', 'Description');

  # set the database table
  $query = db_select('projects', 'p')->extend('PagerDefault');

  # get the desired fields from the database
  $query->condition('user_id', get_user_id())
        ->fields('p', array('id', 'name', 'project_count_type', 'last_updated', 'description'))
        ->orderBy('last_updated', 'DESC')

  # execute the query
  $results = $query->execute();

  # build the table fields
  $rows = array();
  foreach ($results as $row) {
    $rows[] = array("<a href=\"/projects/edit/" . $row->id . "\">" . $row->name . '</a>',
  $output = theme('table', array('header' => $header,
                  	         'rows' => $rows ));

  # add the pager
  $output .= theme('pager');

  return $output;


The only thing I haven't included in this example is the get_user_id() function, which I use to get the Drupal user id.

As I've mentioned here before, the correct way to build an HTML table is with the Drupal theme function (and specifically not calling the theme_table function), as shown in this line of code:

$output = theme('table', array('header' => $header,
                               'rows' => $rows ));

Drupal table example - Summary

I hope this Drupal form/module table example has been helpful. I'll continue to update it as I learn more, including how to make the table columns sortable.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.