#tree
Creates a hierarchy of values in the submit handler of a form.
Compare:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['container'] = [
'#type' => 'container',
];
$form['container']['some_value'] = [
'#type' = >'textfield',
];
// Submit buttons etc. not shown
return $form;
}
This will create a form element. After clicking submit, the key of the form element is used to return the value. in this case, the key is some_value
, meaning validation and submit handlers can retrieve the submitted value with form_state->getValue('some_value')
.
Now, add #tree
to the container:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['container'] = [
'#type' => 'container',
'#tree' => TRUE,
];
$form['container']['some_value'] = [
'#type' = >'textfield',
];
// Submit buttons etc. not shown
return $form;
}
With this change, $form_state->getValue('some_value')
will return nothing, as the value is now part of the container element (the #tree
element) and needs to be retrieved relative to that:
// Returns an array with a single key, 'some_value', that contains the
// submitted value.
$form_state->getValue('container')
// Returns the submitted value:
$form_state->getValue(['container', 'some_value'])