Score:1

Storing temporary data in a form AJAX callback

in flag

I have a form submit button that when clicked fires an AJAX callback.

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Title...'),
  '#ajax' => [
    'callback' => '::getResponse',
    'wrapper' => 'wrapper',
  ],
];

In the AJAX callback, I would like to save what the user entered, plus what the API responded with. I have tried using form state storage and $form_state->set, but in both cases the values are lost.

Form AJAX callback:

  public function getResponse(array &$form, FormStateInterface $form_state) {
    // API call here...

    $form['response']['#value'] = trim($result["answer"]) ?? $this->t('No answer was provided.');
    return $form['response'];
  }

Is there a way to update the UI and the form state?

Jaypan avatar
de flag
How/where do you want to use this data? Do you want to pass it back to the front end to use in the ajax response or by some other JS? Or do you want to store some data to use when processing the form submission or whatever?
Kevin avatar
in flag
Don't want to save it to the database, just use it in the next form submission. So the next time the form submits, I have the previous user input and API response.
Score:1
de flag

Data can be stored in the form submission using $form_state->set('[ARBITRARY KEY]', $value), then retrieved when the form is rebuilt with $value = $form_state->get('[ARBITRARY KEY]'). On the first form build, $value will be null, as the form has not gone through the ajax yet. On further #ajax rebuilds, $value will contain the value you set in the submit handler. Note that you will have to store the value on the form state in the submit handler, NOT the #ajax callback.

Kevin avatar
in flag
How can you have an ajax callback on a submit handler, then?
Jaypan avatar
de flag
Submit handlers are called before the ajax handler(s).
Kevin avatar
in flag
Ah, gotcha. That works now.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.