The elusive HTML ‘id’ attribute when using <g:form>
April 14, 2008 – 1:07 pmIn most Grails tags, the usual HTML attributes get passed through to the output HTML, for example the ‘class’ attribute below:
<g:textField name="name" class="inputField" value="${book?.name}" /> results in: <input type="text" class="inputField" name="name" value="" id="name" />
I tried to do this with a g:form tag and passed in an “id” attribute so I could reference the form in javascript. But you can’t pass an id attribute to the g:form tag because the “id” attribute is reserved for the id of the domain object you’re dealing with:
<g:form action="save" method="post" id="bookForm"> results in: <form action="/form/book/save/bookForm" method="post" > instead of this (like what I was hoping for): <form action="/form/book/save" method="post" id="bookForm">
As a workaround I abandoned the g:form tag whenever I needed to pass through an “id” attribute and just wrote a standard HTML <form> tag instead…until I noticed that the “name” attribute of g:form is also output as the “id” in the generated HTML. So now, I just write a g:form tag with a “name” attribute and end up with the result I’m looking for! Here’s the example:
<g:form action="save" method="post" name="bookForm"> results in: <form action="/form/book/save" method="post" name="bookForm" id="bookForm" >
“bookForm” shows up in the HTML code as both the name and the id of the HTML form tag.

One Response to “The elusive HTML ‘id’ attribute when using <g:form>”
I found that disturbing when I first ran into it as well. Why id?? why not some other name and leave the “id” attribute to fall through. I guess in the end its no big deal, but on my current project we’ve got a front-end guy but the id field was really throwing him for a loop.
for some reason he was hung up on “action” as well…not sure why…
Anyway its good to know I wasn’t the only one who thought that as odd, and I see we both skinned that cat in the same way.
By ryan on Apr 16, 2008