Question

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.

Below is the ajax that I am using:

```
$form['images'] = [
  '#type' => 'container',
  '#id' => 'images',
];

dpm($form_state->get('image_deltas'));

$form['add_another'] = [
  '#type' => 'button',
  '#value' => t('Add Another Image'),
  '#ajax' => [
    'callback' => [$this, 'addAnotherImage'],
    'wrapper' => 'images',
  ],
  '#submit' => [[$this, 'addAnotherImageSubmit']],
  '#limit_validation_errors' => [],
];

Then on the form submit handler, I have this:

public function addAnotherImageSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->set('image_deltas',5);
  $form_state->setRebuild();
}

And on the ajax callback, I have

public function addAnotherImage(array &$form, FormStateInterface $form_state) {
  return $form['images'];
}

I updated the code to reflect the current implementation of it. The dpm prints on form submission, except it's empty.

Was it helpful?

Solution

This:

'#submit' => [$this, 'addAnotherImageSubmit'],

Should be this:

'#submit' => [[$this, 'addAnotherImageSubmit']],

Submit handlers are only called for #type submit and not #type button, so you'll need to change the type.

You will also need to use $form_state->set(), rather than a property on the class. This is because the form class is re-instantiated for each iteration (build, validate, submit), and therefore values stored in the properties of the form class will not persist. $form_state->set() persists values, as these are stored in the database, and are repopulated for each instance of the form class (as long as you call $form_state->setRebuild() as you have done).

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top