drupaldrupal-6drupal-fapi

Form elements as arrays in Drupal


Using Drupal 6.20.

We can setup some form elements like this:-

<input type="select" name="somename[]"><option>ohai</option></select>

and then cycle through them in PHP with

foreach ($somename as $name) { ... }

I am trying to do the same in Drupal. I have a list of select-elements that are identical in style. The number of elements may change in the future so the form processing has to be dynamic.

If I use the above approach, each element will overwrite the preceding one, so that ultimately only one element is printed to the screen. I can't write name="somename[$someid]" as that will not interpret $somename as an array.
Does Drupal support this or am I doing it worng?

Also, Is there any other alternative to achieve the same?


Solution

  • Here is an example to achieve what you are trying to do.

    
    function test_form( &$form_state )
    {
      $form = array();
      $delta = 0;
      $form["test_field"]["#tree"] = TRUE;
      $form["test_field"][$delta++] = array(
            "#type" => "textfield",
            "#title" => "Title",
        );
      $form["test_field"][$delta++] = array(
            "#type" => "textfield",
            "#title" => "Title",
        );
      $form["test_field"][$delta++] = array(
            "#type" => "textfield",
            "#title" => "Title",
        );
      $form["submit"] = array(
            "#type" => "submit",
            "#value" => "Submit",
        );
      return $form;
    }
    

    In your submit & validate function, you will get an array of values under your field's name.

    Remember, enabling #tree on your element is the key to this approach. Also Drupal's form API is one of the best forms framework I have worked with.

    Hope this helps.