How to programmatically create a form tree in Drupal

| | 1 min read
When you work on forms in Drupal where you want to have the same form array elements used multiple times in a form you can use the concept of for form tree. For example if you are working on a purchase order form where you want to have multiple rows of product information like say product name, product code, quantity, price etc, for each product added to the form. This can easily be done using the form tree as follows.
function example_form(&$form_state) {
  foreach ($array_var as $key => $value) {
    $form[example']['form'][$key]['text'] = array(
      '#type' => 'textfield',
      '#default_value' => ,
      '#parents' => array('form', $key, 'text'),
    );
  }
  return $form;
}

function example_form_submit($form, &$form_state) {
  foreach($form_state['form'] AS $key => $value) {
  }
}
In the form submit function you can iterate through the elements as usual.