Last updated August 17, 2010. Created by Steven Jones on May 26, 2008.
Edited by eltermann. Log in to edit this page.
It makes sense to group related fields together, both visually on rendered pages, and in the description of the form in the array. Drupal provides easy ways in which to accomplish both of these tasks.
Grouping in the form array
You can easily group elements together in the form array, by simply using multidimensional arrays:
<?php
$form['group1']['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
);
$form['group1']['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name'),
);
?>These two textfields will then be grouped together, and provided that the form is using Drupal's default theming functions, they will appear next to each other on the rendered page. This grouping is why the # is so important for attribute names.
When submitted the $form_state collection will be populated with valid submitted values and passed to submit handlers, but by default you will not get back the structure of the original form. For example if I submitted the form above, $form_state would contain:
<?php
array(
'first_name' => 'Steven',
'last_name' => 'Jones',
);
?>Note that all concept of group1 has been lost. If however, you want to have the grouping present in the $form_state collection too, then you'll need to set the #tree property on the parent, thus:
<?php
$form['group1'] = array(
'#tree' => TRUE,
);
$form['group1']['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
);
$form['group1']['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name'),
);
?>And again, when I submit, $form_state would contain:
<?php
array(
'group1' => array(
'first_name' => 'Steven',
'last_name' => 'Jones',
),
);
?>You can have groups of groups of groups...etc. and Drupal won't mind.
Adding visual grouping
Sometimes you'll want to groups form elements together in a visual way, e.g. with a box around the different form fields in the group. Drupal provides the #fieldset form element to do just that. We'll need to group our elements together as above, but instead of just having an empty 'parent' element, we'll give it some structure too:
<?php
$form['group1'] = array(
'#type' => 'fieldset',
'#title' => t('Your Name'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['group1']['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First Name'),
);
$form['group1']['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last Name'),
);
?>This would be rendered as a group of two text boxes with a title of 'Your Name'. The two properties #collapsible and collapsed allow you to specify if users should be able to use javascript to temporarily hide the group of elements, and if the elements in the group should be hidden by default respectively.