Build Drupal Form Elements BEFOR the AJAX Callback is Called

I just lost two days of productive development time trying to figure out why AJAX was breaking in one of the steps of a form I am building in Drupal. As it turns out, a very important, and not at all obvious, thing to remember when developing a Drupal form is that the Drupal Forms API needs to define the form fields BEFORE the AJAX callback is fired.

The form I was working on was up until now, being built in such a way that this was not a problem. However, when I started working on a select element that uses AJAX to call an undetermined number of subsequent select elements, I decided to put that logic inside of the callback function. That was a “bad move”. The callback function needs to call upon a $form array that has already been built. Logically, I figured that I could just add to the existing $form array before returning it via the AJAX callback function. After all since I ad not yet returned it, why not? Well the reason why not is buried somewhere in the Drupal Forms API I suppose.

So, be sure to build the form elements into the $forms array prior to the AJAX callback function getting called.

Leave a Reply

Your email address will not be published.