Module Development: Adding Form Fields via AJAX/AHAH

Published May 20, 2009

Adding form fields to a Drupal form dynamically is not the most straight-forward task. You'll see this occasionally on a Drupal form (poll module jumps to mind) when there is an "add another" button that (seemingly) simply adds another set of input elements to the form. The big sticking point in setting this functionality up is doing it in a way that keeps FormAPI's security intact. Fortunately, there's some tips to get you mentally started.

I say "mentally" because the process doesn't really involve adding form fields - it is actually an exercise in manipulating FormAPI's $form_state array. You see, the $form_state variable is the key to keeping the security system happy. If the $form_state variable doesn't agree with the form that is submitted, bad things happen. Once you accept this, then the process makes a whole lot more sense.

Basically, what happens when the user clicks the "add another" button is the $form_state variable is modified with the new form fields. FormAPI then uses this updated $form_state to re-generate the form and send back the updated portion via AHAH.

There's an invaluable page at Drupal.org with all the details. In addition, I've found the source code of the Quicktips module a great source of reference as well.

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name
CAPTCHA