I have a multi-step form using AJAX. When you submit the form it increments the step, and then sets $form['#rebuild'] to TRUE, and the entire form is replaced by AJAX.

It works fine, right up until one of the steps involved calling user_login_finalize() in the submit handler - the user can go from anonymous to logged in. Then when it tries to build the next step I get the error:

Form errors cannot be set after form validation has finished

I puzzled over this error for a while. I thought the validation handler might be firing twice, but then I saw in the debug trace that setInvalidTokenError() is being called in FormBuilder->doBuildForm().

After looking in doBuildForm(), I think the problem is that Drupal thinks the form is being submitted in a naughty way or has the wrong token. What can I do?


The only way I could fix it was to set $form['#token'] to FALSE when building the form. This disables the token checking functionality, which isn't ideal, but I think it's my only option.


Make sure, you do not have $form_state->setRebuild() calls inside final submit handler. Use it only for AJAX or steps in multi-step forms. Because, if it used in the submitForm() callback or any other, and this is the last one, and the form has something to do with authentication, the form will rebuild, but the user will be already authenticated. And here is the problem strikes. The forms for authenticated users must contain token, but your form is rebuilt, and initially, this form was built for anonymous user.

I.e. If you use AJAX, set rebuild mark only in ajax callback, not in the submit callback. If you create a multi-step form, use rebuild only to submit callbacks which affect steps (next, previous), etc., but don't call it for the last step submission.

P.s. My answer obviously is too late. But having the same problems now and figured out how to fix it. So maybe it will save some time who will google it in the future.

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.