David Powell

Communications + Community Services Consultant, QLD Australia

Writing table headers on the fly using drupal's theme_table

Anyone whose new to writing their own modules for Drupal (like me) might sooner or later (probably sooner) come across Drupal's very nifty theming system. Tonight I wanted to spit out a table of results from a dynamically generated query. After a quick search I found drupal's theme_table function and it looked perfect, except for one problem. The examples of how to use the theme_table() function all assumed you knew what your tables headers would be.

For example consider this bit of (beautiful) code that mecano posted on the Drupal API documentation page for theme_table:

<?php
function _mymodule_somepage_callback($nid) {
  $query = db_query("SELECT id, look, taste FROM {mytablename}");
  // This next line was the problem for me -
  $header = array('ID', 'Look', 'Taste');
  $data = array();
  while ($row = db_fetch_array($query)) $data[] = $row;
  $output = theme_table($header, $data);
  return $output;
}
?>

The problem for me was that I don't even know in advance which columns I'll need to generate headers for ( it's related to the nature of the module). So how was I going to tell theme_table() what headers I wanted?

Then in the deep dark recesses of my memory (it's been a few years since I've written any serious code and I'm VERY rusty) I remembered array_keys(). I can get the result of my query into an array easily enough, and then array_keys pulls out the column names. Perfect!

So all I needed was a very small change to the code above to generate table headers dynamically based on the results of a query... here's some example code that will give you an idea.

<?php
function mymodule_sql2table($sql) {
  $result = db_query(
$sql);
  // Use the array_keys function to pull out the column names from the result
  $header = array_keys(db_fetch_array($result));
  $data = array();
  while ($row = db_fetch_array($result)) $data[] = $row;
  $output = theme_table($header, $data);
  return $output;
}
?>

 

About my blog...

A blog about lots of things - social justice, community services, technology, education and chocolate.

The ideas, views and opinions expressed on this site are entirely my own unless I specifically state otherwise. Nothing on this website, or of any websites I own, represents the views, opinions or positions of any organisation that I am associated with as an employee, consultant or director.

Login


© 2010-2011, David J. Powell

Site by Service Connect
(Template by JoomlArt).

Contact Details

Phone   0434 932 430   Skype   d.j.powell
Email     Twitter

  http://twitter.com/moondrake

Web   www.davidjpowell.com     http://au.linkedin.com/pub/david-powell/7/6a7/4a9