Form token wrong if logging in during rebuild 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-&gt;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.