Hello,

I am having problems with a custom form and using session variables to create inline form errors. I am at complete loss how to do this and really need some help.

As you know the validateForm method is where we check the form submissions that users enter and validate each input field. For this project, all validations must be server-side. At the end of the valdiateForm method, if an error has occurred, I then store the array that is returned from $form_state->getErrors() into a session variable. The obvious next step is that the buildForm page is called to re-render the form. It is here where I check the session variable to see if any errors has occurred and thus write the individual error message to the appropriate field.

The problem is that upon this postback, nothing is in the session variable. It's only when I submit the form again that the session variable contains the stored error messages. Checking the contents of the sessions table reveals that it is being populated correctly and at the right time but again, upon the post-back nothing is in the session variable until I either resubmit it or refresh the page.

I tried doing this with Private Store and the same thing has occurred. I even created a custom table for this to store my error messages and again with the same problem. The real issue is that I cannot access the error messages that is going to the Status Message window because these are wiped clean before my form is rendered.

Thus either the problem is with cache (Drupal and TWIG caches are turned off) or there is something I do not understand about the life cycle of the Form API as well as Session Management.

I am of desperate need of ideas here.

Thanks!

Comments

Jaypan’s picture

Drupal already handles error handling for you. You just need to use form_set_error() on the field to which the error occurred.

dotmundo’s picture

Perhaps I was not clear:

My requirements are to create inline error messages. That is place the error message underneath the input field. The status message window at the top will also remain. In either case form_set_error does not exist in Drupal 8 and instead it is FormState::setErrorByName.

dotmundo’s picture

I really could use some help here. Thanks!

dotmundo’s picture

I came up with a much more simpler and alternative solution of which I describe fully here

https://www.drupal.org/node/2835888