I created a custom module which contains a Class Form. When I submit my form, I redirect the user to the form page. During the submission, I need to save a form_state
variable to re-use it after the user is redirected to the form.
So, from my submit method, I save my variable (with "$form_state->set(...)
" ) and I add "$form_state->setRebuild()
".
All works perfectly. Now, I want preserve my variable AND empty some field's form. I don't want to preserve values of all fields of my form after the user has been redirected.
I tried this :
// From my buildForm
// ...
$form['test'] = [
'#type' => 'textfield',
'#title' => "test",
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
$form_state->setValueForElement($form['test'],"0");
}
return $form;
But I have this error when I use the setValueForElement method :
The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Component\Utility\NestedArray::keyExists() must be of the type array, string given, called in /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in Drupal\Component\Utility\NestedArray::keyExists() (line 259 of core/lib/Drupal/Component/Utility/NestedArray.php).
I don't understand where my mistake is, use the setValueForElement maybe not the better way?
Edit (after Ismail Cherri's answer)
This is my new code : ("$form['#parents'] = array();" added)
// From my buildForm
// ...
$form['test'] = [
'#parents' => [],
'#type' => 'textfield',
'#title' => "test",
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
$form_state->setValueForElement($form['test'],"0");
}
return $form;
I keep the same error when I submit my form...
The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Component\Utility\NestedArray::keyExists() must be of the type array, string given, called in /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in Drupal\Component\Utility\NestedArray::keyExists() (line 259 of core/lib/Drupal/Component/Utility/NestedArray.php).
test
field in above form, e.g.$form['test']['#parents'] = array('status');