4

I want to add some arbitrary variable to store it in the form_state and use it again so in one of my ajax callback functions I set a property named var:

public function MyFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = array('1'=>'one','2'=>'two');
$form_state->set('var', $terms);
....
}

it works and the storage array of the form_state has var element

unfortunately when trying to get the var back inside another callback function it returns null. actually with debugging the storage array of the form_state is empty

public function MyOtherFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = $form_state->get('var');
....
}
0

You can't change $form or $form_state in an ajax callback. There is no more code coming after the callback, that could process this. The only purpose of the ajax callback is to prepare and return an ajax response.

  • then how to save my var in another way? – Emad Karhely Sep 24 '16 at 8:27
  • 1
    You could use a session variable. Then it will survive until the next request. But the ajax callback is not the right place for form logic. Build the form the same way like a normal form without ajax. – 4k4 Sep 24 '16 at 9:00
2

As 4k4 mentioned, you cannot change the form state inside an ajax callback function.

You can, however, change it in the ajax button submit function.

$form['ajax_button']['#submit'][] = [static::class, 'ajaxButtonSubmit'];

public static function ajaxButtonSubmit($form, $form_state) {
  //...
}
0

I would like to avoid using PHP session variables here since it is easy to get mixed with other forms. Especially if the user wants to keep this form open and tried to open another form.

Instead of PHP session variables, you may try to change the logic and move your code to a validation callback for the whole form. And from there you can set form state values.

$form['#validate'][] = '::handleInputs';

Since probably what you need is part of validating the user inputs and showing specific options depend on user inputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.