Naming Form Items In Drupal

Photo of Greg Harvey
Mon, 2009-06-15 12:38By greg

There is an issue with the Drupal Forms API in Drupal 5.x. It assumes there is one form on a page so it does not handle duplicate form IDs very well (read, at all!) - as such, if your forms are loaded in blocks or you just drupal_get_form() to load extra forms on a page in Drupal 5.x, you might well find yourself with several submit buttons all with an ID of id="edit-submit". Which sucks!

As such, as a module developer you need to be careful. I guess the only way to be sure your form IDs don't trip over other form IDs in Drupal 5.x is to use the namespace of your module in CVS to prefix your form field names. So, using my CCK Gallery module as an example, my submit button might be called "cck_gallery_submit" instead of plain old "submit". This way I can be sure it will be unique, generate a unique HTML ID and created valid mark-up.

Fortunately this is (nearly) fixed in Drupal 6.x, so if Drupal 6.x finds more than one item form item on a page to be built with the same name, it will append an incrementing number to the items concerned. E.g. if there are several form items on different forms called "submit", the first one will have id="edit-submit-1", the next id="edit-submit-2", etc.

Unfortunately, and as Sean just pointed out in IRC, this still doesn't work if you call your form using AJAX. To quote him, "When the form is loaded via ajax Drupal is seeing one page load = one form". Doh!

So we do still need to be careful. One to be aware of, definitely.