I am building a form using formBuilder. I have tried two methods to store values across form submit/validate for usage in ajax callbacks, but have been unsuccessful in either.
The first method, was to store a value in $form_state->set('name','value'); and retreiving it in the form submit/validate handler. That returned an empty result.
The second method was to store a variable on the class itself protected $image_deltas = 0;
and then when the ajax form submit/validation is triggered, $this->image_deltas++; However, when I do this, it still does not work.
The following is the code I am using.
$form['images'] = [
'#type' => 'container',
'#id' => 'images',
];
dpm($this->image_deltas);
for ($i=0;$i<=$this->image_deltas;$i++) {
$form['images'][$i]['image'] = [
'#type' => 'textfield',
'#title' => t('Image Path:'),
];
}
$form['add_another'] = [
'#type' => 'button',
'#value' => t('Add Another Image'),
'#ajax' => [
'callback' => [$this, 'addAnotherImage'],
'wrapper' => 'images',
],
'#submit' => [$this, 'addAnotherImageSubmit'],
'#limit_validation_errors' => [],
];
The form submission handler is the following.
public function addAnotherImageSubmit(&$form, FormStateInterface $form_state) {
$this->image_deltas++;
$form_state->setRebuild();
}
The AJAX callback is the following one.
public function addAnotherImage(&$form, FormStateInterface $form_state) {
return $form['images'];
}
When I submit the form, dpm()
prints 0 every time. The same thing happens if I use $form_state->set('image_deltas')
and $form_state->get('image_deltas')
.