Form elements as arrays in Drupal

7.6k views Asked by At

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?

2

There are 2 answers

1
SarfarazSoomro On BEST ANSWER

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.

0
Max On

I know this question was answered but I think there's an easier way which is less verbose and you only need to change the number of fields (or pass it as an argument when getting the form).

function test_form() 
{
    $form['#tree'] = TRUE; // This is to prevent flattening the form value
    $no_of_fields = 5;     // The number of fields you wish to have in the form

    // Start adding the fields to the form
    for ($i=1; $i<=$no_of_fields; $i++)
    {
        $form['somename'][$i] = array(
            '#title' => t('Test field no. '.$i),
            '#type'  => 'textfield',
        );      
    }
    // Add the submit button
    $form["submit"] = array(
        "#type"  => "submit",
        "#value" => "Submit",
    );  
}

When submitting your $form_state['values'] will contain (among other things) your form elements value as an array:

  'somename' => 
    array
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '' (length=0)
      5 => string '' (length=0)