I'm noticing that hook_form_alter isn't being called when a page has errors that display a message from form_set_error. Changes to my form aren't taking effect, and the error page is effectively broken.

I've tried to output a dpm statement in hook_form_alter, but it isn't appearing on the error page.

Is there a way to get drupal to call the hook and alter the form?


1 Answer 1


Forms are cached in Drupal so the form is loaded once (where your form_alter runs) and then it's loaded from cache to be reloaded when there are validation errors.

You should use an #after_build callback, which always gets run.

Just remember to return $element in your #after_build callback or you'll be getting WSODs.

  • is it possible to add elements to the form? I'm adding a textarea when a value is set in a particular field.
    – Arosboro
    Apr 15, 2012 at 4:18
  • Technically yes you can do anything with the form. That said, you might be better off adding the field in your form alter with #access FALSE and then setting it to TRUE in your after build if necessary.
    – Alex Weber
    Apr 15, 2012 at 4:20
  • If I add the field in the form_alter, it doesn't appear on the validation error page. I decided to create the field in my after_build callback, but the #ajax callback is not being fired. Autocomplete works fine. When dealing with form_alter I found that I had to add the wrapper with #printed => TRUE to the root of the array, and then copy the field to the element I wanted it to display under. I think the callback worked then because the field had already been recognized during rendering. Do I need to call field_default_form or some other function to get ajax callbacks to work?
    – Arosboro
    Apr 15, 2012 at 15:40
  • Could you please elaborate on exactly what you are trying to do with adding the extra field? It doesn't appear in your validation error because #access was set to false, you could try checking for form_get_errors() in your after build and setting #access to true if there are any
    – Alex Weber
    Apr 15, 2012 at 16:28
  • I'm writing a module called text_field_reference that autocompletes to the value of a field in the recommendation content type I've created. The recommendations match up to a finding select field that has integer point values (0, 1, 2, etc). If the user changes the select field, I use an ajax call to display a textarea that autocompletes to a recommendation. Its blur event replaces the field_text_reference field with a key representing the node that was referenced. I'll be the first to admit it's kind of hackish. The ajax callback to replace the reference field is intermittently working.
    – Arosboro
    Apr 15, 2012 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.