Reputation: 2406
In Drupal 8, I don't understand how build a "hierarchical" form.
I have this sample form
...
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = array(
'#type' => 'fieldset',
'#title' => t('Main description'),
);
$form['description']['subfirst'] = array(
'#type' => 'textfield',
'#title' => t('subfirst'),
);
$form['description']['subsecond'] = array(
'#type' => 'textfield',
'#title' => t('subsecond'),
);
$form['content'] = array(
'#type' => 'fieldset',
'#title' => t('Main description'),
);
$form['content']['subfirst'] = array(
'#type' => 'textfield',
'#title' => t('subfirst'),
);
$form['content']['subsecond'] = array(
'#type' => 'textfield',
'#title' => t('subsecond'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
dpm($form_state->getValues(),"getValues");
}
...
When I submit my form, my form_state->getValues() return :
The form_state->getValues()
contains only the ['content']['subfirst']
and ['content']['subsecond']
values...
That means I must use uniques labels with the form api ? I find it weird...
Then, I change my form :
$form['content']['subfirst'] become $form['content']['totosubfirst']
$form['content']['subsecond'] become $form['content']['todosubsecond']
The new code :
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = array(
'#type' => 'fieldset',
'#title' => t('Main description'),
);
$form['description']['subfirst'] = array(
'#type' => 'textfield',
'#title' => t('subfirst'),
);
$form['description']['subsecond'] = array(
'#type' => 'textfield',
'#title' => t('subsecond'),
);
$form['content'] = array(
'#type' => 'fieldset',
'#title' => t('Main description'),
);
$form['content']['totosubfirst'] = array(
'#type' => 'textfield',
'#title' => t('subfirst'),
);
$form['content']['totosubsecond'] = array(
'#type' => 'textfield',
'#title' => t('subsecond'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
And when I submit my form, my form_state->getValues() return :
I get the four values. But, they are in the same hierarchical level. How I use the form api for have a form_state like this :
'description' => 'subfirst' => string(3) "AAA"
'description' => 'subsecond' => string(3) "BBB"
'content' => 'totosubfirst' => string(3) "CCC"
'content' => 'totosubsecond' => string(3) "DDD"
?
I want get a hierarchical form_state because after I want create a custom function like :
foreach element in description
do that
foreach element in content
do that
...
Upvotes: 2
Views: 1651
Reputation: 2406
Set #tree => TRUE on the parent elements, then the values will be nested accordingly
Upvotes: 4