Creating an array of form elements

Last modified: March 9, 2006 - 19:57

As someone who's done a lot of work with the "old" form methods, the new Forms API is a lot of new information to chew on. Almost everything is different. In the spirit of practicality, here's how I solved the riddle of "how to I make an array of form elements?" The answer is #tree.

In this case I want to create an array of select fields to assign one of a pre-defined set of values to a given piece of data. It's meant to help assign CVS field headers (and the content in their columns) to node data rows. Another example might be a mass-categorization page for lots of posts.

Here's the code before:

<?php
$fields
= array('pre', 'defined', 'values', 'to', 'assign');
foreach (
$array_of_stuff as $i => $value) {
 
$output .= form_select('', 'assign]['. $i, $edit['assign'][$i], $fields));
}
?>

Here's the code after:

<?php
$form
['assign'] = array('#tree' => 1);
$fields = array('pre', 'defined', 'values', 'to', 'assign');
foreach (
$array_of_stuff as $i => $value) {
$form['assign'][$i] = array(
       
'#type' => 'select',
       
'#title' => '',
       
'#default_value' => $edit['assign'][$i],
       
'#options' => $fields
     
);
?>

I'm sure all this information is contained in the big docs about Forms API, but it can be a bit dense. I hope this helps people in getting to know the new API, which offers a lot more power once you learn it's ins and outs.

 
 

Drupal is a registered trademark of Dries Buytaert.