Drupal 7: theming forms with tables

This is a quick guide to using tables for layout of forms in Drupal 7 without being naughty. Posted by Thomas Sutton on July 11, 2011

There are a few different ways to use tables to layout Drupal 7 forms. The most commonly described method (indeed, it’s used in the core [tableselect][1] form field type) is to create a custom form field type that can process it’s children and render as a table. This is pretty limiting (tableselect, for instance, is pretty much just a select field).

Another approach is to use #prefix and #suffix to wrap each field in the table with the appropriate HTML tags to build the table. This, though, means that changing the weights of elements, adding and removing elements, or making pretty much any change to the form might result in invalid or completely broken markup.

The approach I think is best is to treat the table similarly to the way the forms API handles fieldsets: as a container with multiple fields within it. This can be a little tricky to get working, but seems to do the trick for me. The approach works like this:

Create a new form element that will be the table:

Then loop over your data to create the rows in the table. This is a little tricky: if you just put your fields straight into $form['people']['#rows'] then FAPI won’t see them (remember that it won’t traverse array components begining with a #) and so won’t process them. On the other hand, you could name your array $form['people']['rows'] but then the FAPI will generate quite noisy field names and add additional values which will confuse theme_table() when it comes time to render the whole lot.

Instead, we’ll use references to build both include the fields in the form (though in a way that they won’t be actually output) and put them in $form['people']['#rows'] so the table will be rendered nicely. This is possible mainly through the use of references!

Assuming you’ve got an array $people containing your data you can loop over them to add the rows to your table like so (and yes, I know this could be structured better):

Now you should have a form full of fields all laid out nicely in a table. Hoorah!

This post was published on July 11, 2011 and last modified on September 4, 2021. It is tagged with: drupal, drupal7, theme, render, forms, tables, ajax, ahah.