Skip to main content
Tree

Drupal form's #tree option

There may be a need to name the form elements in an array structure how the form is built. You can see this in Ubercart checkout pane form's input elements. This is very useful when one has a large multi-part form which can be grouped easily by their POST content's array format.

Eg: panes[delivery][delivery_first_name]

A simple flag on you $form construct array will do the trick. It's the #tree option. For whichever elements you set this #tree option, the element's children will be named with full reference to its parents.

  $form['panes'] = array('#tree' => TRUE);
  $form['panes']['delivery'] = array(
      '#type' => 'fieldset',
      '#title' => t('Delivery Address'),
      '#attributes' => array('id' => 'delivery-pane'),
  );
  $form['panes']['delivery']['delivery_first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First name'),
  );

Here, delivery_first_name input element when rendered will have a name = "panes[delivery][delivery_first_name]", as one of it's parent is have #tree set to TRUE. Hope this helps someone looking to implement a similar functionality.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.