Score:0

Need to pass $variable from validateForm back to form even if validation fails

ru flag

It is a multipage Ajax form and I need to alter elements in a page based on form validation . This means, even if validation fails and the form stays on the same page, I need to visually alter that form page. Setting a field error with $form_state->setErrorByName is not sufficient for me so I'm exploring other options that I can't seem to find :)

I've tried using $form_state->set() and $form_state->setTemporary() but it seems the values set this way are only set if the validations passes. If validation fails, I get NULLs back in buildForm.

I've also tried storing to Drupal session, which works, but not as expected since my form is an Ajax form and the session variable would only be available on a second submit and would persist one step further than needed.

And I'm out of options.

Any suggestions?

PS I'm on Drupal 10.

Score:1
cn flag

You can set values in $form_state, the problem is the timeline when buildForm() is executed.

For a multistep form the form is only rebuilt if it is error-free. So the solution would be to not set an error but rebuild a different version of the form including your custom error messages by setting:

$form_state->setRebuild();
Trudog avatar
ru flag
yes, this would work. Thank you!
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.