Naming Form Items In Drupal

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.

Another caveat in Drupal 6...

Another problem in Drupal 6 is that you can't always guarantee what order the forms will load, especially in cases where you load forms using AJAX. If your form loads BEFORE the default search box, your submit button's ID will be edit-submit, but if it loads AFTERWARDS, it will be edit-submit-1. It might load before initially, but after if the form fails validation, for example.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.