Create Simple Tables

This is a brief tutorial on how to use the built-in functions to build a table in Drupal.

Let me note, for those who are thinking about complaining, I know that there are things in this sample that do not conform to Drupal coding standards. Get over it. This is not a tutorial on those standards; nor is it a tutorial on localization either. However, this code should all work as written (unless you're using the Weight module).

The Task

We want to create a page that shows some information about all of our content (okay, nodes) in a tabular format. We need the stuff that is promoted to the front page and sticky listed first.

Now we all know that the boss who requested this didn't specify a lot of things he really wants. So we'll start with what he asked for, then embellish it when he starts saying, "But I need this column done this way..." We've all been there, even if we are that boss.

<?php
  $header
= array('Node ID', 'Title', 'Type', 'Terms', 'Created', 'Published', 'Sticky', 'Promoted');
 
$rows = array();
 
$noyes = array('No', 'Yes');

 
$results = db_query("SELECT * FROM {node} ORDER BY promote DESC, sticky DESC, created DESC");

  while (
$node = db_fetch_object($results)) {
   
$termlist = taxonomy_node_get_terms($node->nid);
   
$terms = array();
    foreach (
$termlist as $key => $value) { $terms[] = $value->name; }
   
$rows[] = array($node->nid,
                   
l($node->title, 'node/'. $node->nid .'/edit'),
                   
$node->type,
                   
implode(' | ', $terms),
                   
format_date($node->created),
                   
$noyes[$node->status],
                   
$noyes[$node->sticky],
                   
$noyes[$node->promote],
                );
   }
  return
theme('table', $header, $rows);
?>

The Basics

Okay that produces the table he asked for, so let's look at what we did.

  • theme('table', $header, $rows) - This invokes the Drupal function to create a table; it's pretty simple to build nice looking tables with it.
  • We used the form "theme('table'..." (as opposed to "theme_table(...") so that our site's theme can be used beyond what we've done here.

  • $header is an array ($header = array('Node ID', 'Title', ...)) that we built above to contain the titles for the columns.
  • $rows is an array ($rows[] = array($node->nid,...)) whose elements we built for each row that was returned from the query.

Uh-oh, here comes the boss! "Nancy, this looks sort of like what I wanted, but can you center the node ID, published, stick, and promoted columns, please?"

Additional Row Attributes

"Sure, boss, no problem." I know how to do this, but I won't let him know how simple it is, so I'll go get a cup of coffee and visit with my friend Sheila down the hall first.

All we have to do is add an extra attribute to each of those cells. Here are the lines we've changed.

    $rows[] = array(array('data' => $node->nid, 'align' => 'center'),
                    array('data' => $noyes[$node->status], 'align' => 'center'),
                    array('data' => $noyes[$node->sticky], 'align' => 'center'),
                    array('data' => $noyes[$node->promote], 'align' => 'center'),

Notice that we can do this by changing each of them to an array and adding an "align" attribute. The actual data is identified with the key "data" and the value is assigned with the array assignment operator "=>". Then we specify each HTML table attribute we want to add, in this case, the alignment element.

[Warning: Some themes will not honor the alignment attribute, but that's easy to fix by using a "class" attribute.]

Separating Rows

An hour later, my boss finds me conferring with Sheila. "Hey, Nancy, this is getting pretty close to what I want, but can you do something to separate the rows? You know like Barney did on that other one where he used a different color. Maybe he can tell you how he did it because it took a lot of time."

After he walks away, I snicker to Sheila, "He doesn't know that table rows are automatically given alternating classes so all I have to do is change the style sheet."

Sheila reminds me, "Yeah, but make sure you don't mess up all the other tables on the site."

That's not a problem, we'll just give this table a different name before we change the CSS. We'll name the table for my boss, Ralph. Here's the first step, where we add an attribute to the whole table.

  $table_attributes = array('id' => 'ralphs-node-table');
  return theme('table', $header, $rows, $table_attributes);

As you can see, there is a another parameter that we've added to the theme function. It tells Theme to add this attribute to the "table" tag.

As I said to Sheila, the theme_table function automatically adds 'class="odd"' and 'class="even"' to the rows on an alternating basis. So now we can go to the end of our style sheet and specify:

#ralphs-node-table .odd {background: #e0f0e0;}
#ralphs-node-table .even {background: #e0e0f0;}

Adding Graphics

The next morning Ralph came and announced, "I had a brilliant thought last night! Instead of yes and no for these columns, let's make it stand out better. How about a nice big check mark for the ones that are yes and just leave it blank for no. Oh, except for the ones that aren't published - let's make them a big X or something." With that and my make-believe grimace of immense pain, he walked.

I laughed because I knew how to do this in just a few minutes, but he thinks it will take me the rest of the week.

Remember, we can specify pretty much any attribute for a cell with the theme_table function. And, if you've ever looked at your site logs, you'll know that such graphics are already available on all Drupal sites. We'll just set a class name for those cells and then specify those graphics to be used. I'm going to do it so his next changes are even easier. So here's the changed code, which uses a little php magic:

  array('data' => ' ', 'class' => $node->status ? 'published' : 'unpublished'),
  array('data' => ' ', 'class' => $node->sticky ? 'sticky' : 'not-sticky'),
  array('data' => ' ', 'class' => $node->promote ? 'promoted' : 'not-promoted')

Note that you add just about any attribute to any cell. I generally try to use classes for everything so that it can be easily changed in the CSS.

So now we just have to set up the style sheet:

#ralphs-node-table .published {background-color: inherit; background-image: url(/misc/watchdog-ok.png);
   background-repeat: no-repeat; background-position: center;}
#ralphs-node-table .unpublished {background-color: inherit; background-image: url(/misc/watchdog-error.png);
   background-repeat: no-repeat; background-position: center;}
#ralphs-node-table .sticky {background-color: inherit; background-image: url(/misc/forum-sticky.png);
   background-repeat: no-repeat; background-position: center;}
#ralphs-node-table .not-sticky {}
#ralphs-node-table .promoted {background-color: inherit; background-image: url(/misc/watchdog-warning.png);
   background-repeat: no-repeat; background-position: center;}
#ralphs-node-table .not-promoted {}

Okay, I cheated. While I was looking up the exact names of those images, I found a "forum-sticky" image. So shoot me!

Final Result

Well, here's how it looks now:

<?php
  $header
= array('Node ID', 'Title', 'Type', 'Terms', 'Created', 'Published', 'Sticky', 'Promoted');
 
$rows = array();
 
$noyes = array('No', 'Yes');

 
$results = db_query("SELECT * FROM {node} ORDER BY promote DESC, sticky DESC, created DESC");

  while (
$node = db_fetch_object($results)) {
   
$termlist = taxonomy_node_get_terms($node->nid);
   
$terms = array();
    foreach (
$termlist as $key => $value) { $terms[] = $value->name; }
   
$rows[] = array(array('data' => $node->nid, 'align' => 'center'),
                   
l($node->title, 'node/'. $node->nid .'/edit'),
                   
$node->type,
                   
implode(' | ', $terms),
                   
format_date($node->created),
                    array(
'data' => ' ', 'class' => $node->status ? 'published' : 'unpublished'),
                    array(
'data' => ' ', 'class' => $node->sticky ? 'sticky' : 'not-sticky'),
                    array(
'data' => ' ', 'class' => $node->promote ? 'promoted' : 'not-promoted'),
                );
   }
 
$table_attributes = array('id' => 'ralphs-node-table', 'align' => 'center');
  return
theme('table', $header, $rows, $table_attributes);
?>

I'm just waiting for Ralph to come in and ask me to add a pager function to this code. I wonder if I can make him think it will take me a couple of days when it will really only take a couple of minutes.

 



Comments

Community type website that needs signup tables

Nancy,
This page makes me think there is hope. What a powerful tool php is.

I suppose administrators have access to the PHP but not the authenticated Members=Committee Leaders who can edit "regions".

So as an Admin1 or Admin2, I could set the PHP table attributes as a standard.

Then somehow give Members-committee leaders who can edit regions, a way to define the table rows array values.
The table name would come from the page name.
Then the table is built and inserted into the "region" somehow.

Then authenticated users (I don't know if we can have this level of user yet) come along and want to Signup.
Or even better, everyone can view the site (all public) but when you click on "Signup" the user must authenticate or register.
Then the user is given a single ROW which they can populate or edit, then save, or delete (until the time a committee leader turns that feature off).
Oh, of course, just like Ralph, I also want to have a 'public' view of the table (some hidden columns) and an 'authenticated view' of the table which is the entire table with all columns showing.

It looks possible, but how to get there.

Thanks for listening to my rambling.
Rick