0

I'm writing a custom module and I am trying to create an array of form fields, but it doesn't seem it is what I am doing.

Here's the code I'm trying to use:

for($i = 0; $i < 3; $i++) {
  $form['contact'][$i]['value'] = array(
     '#type' => 'textfield',
     '#title' => 'Contact Name',
     '#size' => 50,
  );
}

Doing this, I was expecting the form to print the field as:

<input type="text" value="" size="50" name="contact[0][value]" />
<input type="text" value="" size="50" name="contact[1][value]" />
<input type="text" value="" size="50" name="contact[2][value]" />

Instead, it outputs:

<input type="text" value="" size="50" name="0" />
<input type="text" value="" size="50" name="1" />
<input type="text" value="" size="50" name="2" />

2 Answers 2

4

Actually, all you need is to do this, but keep in mind this also changes how the values get returned in your form submit functions (you'll get a nested array rather than separate values in $form_state['values']).

$form['contact']['#tree'] = TRUE;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Didn't know that was even an option
0

The answer provided is exactly what i needed. This is my code, which will probably help future developers.

$form['results']['subject'] = array(
    '#tree' => TRUE
);

foreach($subjectList as $subject) {
    $form['results']['subject'][$subject->id] = array(
        '#type'      => 'textfield',
        '#title'     => $subject->name, 
        '#maxlength' => 3, 
        '#required'  => TRUE,
    );
}    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.