0

I built a form in a form plugin like so.

public function buildForm(array $form, FormStateInterface $form_state) {
$array[0] = 'value1';
$array[1] = 'value2';
$array[2] = 'value3';
$array[3] = 'value4';

$form['field_1'] = [
    '#type' => 'value',
    '#value' => 'test value',
];

foreach($array as $item){
    $form['fields'][$item] = [
        '#type' => 'textarea',
        '#title' => $item,
    ];
}
    $form['actions'] = [
        '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
}

The form is built just fine and I can return the values upon submit like so,

public function submitForm(array&$form, FormStateInterface $form_state) {
    die(print_r($form_state->getValues()));
}

This is part of the output I receive

[field_1] => test value
[value1] => User input for value 1 text area
[value2] => User input for value 2 text area
[value3] => User input for value 3 text area
[value4] => User input for value 4 text area
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The issue is, I want value1,value2,value3, and value4 to appear as children in the ['fields'] part of the array.

To demonstrate, I'd want the output to appear like so.

[field_1] => test value
[fields] => [
    [value1] => User input for value 1 text area
    [value2] => User input for value 2 text area
    [value3] => User input for value 3 text area
    [value4] => User input for value 4 text area
]
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The ultimate goal is to be able to use a foreach loop on the fields array, like this

foreach($fields as $key => $value){
    print_r('This is the key: '.$key.' and this is the value: '.$value);
}

I also attempted declaring 'fields' as a container first like so

$form['fields'] = [
    '#type' => 'container',
];

but it has no effect. How would I group form elements into an array when parsing the form state?

1 Answer 1

3

If you group the fields below $form['fields'] you also have to set #tree at the top of the array:

$form['fields']['#tree'] = TRUE;

Then the values will be structured in the same way as the form elements.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.