Community Documentation

Creating an array of form elements

Last updated March 9, 2006. Created by joshk on March 8, 2006.
Edited by sepeck. Log in to edit this page.

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.

About this page

Drupal version
Drupal 4.7.x

Archive

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.