Search code examples
htmlgrailsgroovygsp

Prevent Grails input tags from adding id attributes


I noticed that some of the Grails tags for generating input elements (g:textField, g:hiddenField, and some others) automatically set the id attribute of the generated HTML tag equal to the name attribute, unless the id attribute is explicitly given.

Is there any way to use those custom tags to produce an HTML tag without an id attribute? I tried setting the id attribute to an empty string but the generated code had the id set to the name.

I know I can do this with custom tags but I am wondering if there is a simpler way.


Solution

  • This doesn't seem to be possible. The source code of the FormTagLib.groovy class shows that there is a flag that decides whether to write id attributes identical to the name if an id was not given. Unfortunately it is turned on and not configurable from outside. See the following code:

    First, we have the source of g:textField which calls fieldImpl

    def textField = { attrs ->
        attrs.type = "text"
        attrs.tagName = "textField"
        fieldImpl(out, attrs)
    }
    

    The method fieldImpl (full source available on Github) calls outputAttributes. Note the third parameter which is true

     def fieldImpl(out, attrs) {
        resolveAttributes(attrs)
        out << "<input type=\"${attrs.remove('type')}\" "
        outputAttributes(attrs, out, true)
        out << "/>"
    } 
    

    outputAttributes looks like this (abbreviated):

    void outputAttributes(attrs, writer, boolean useNameAsIdIfIdDoesNotExist = false) {
        attrs.remove('tagName') // Just in case one is left
        attrs.each { k, v ->
          ...
        }
        if(useNameAsIdIfIdDoesNotExist) {
            outputNameAsIdIfIdDoesNotExist(attrs, writer)
        }
    }
    

    This method calls outputNameAsIdIfIdDoesNotExist... which will generate the actual id. As outputAttribues always receives true, nothing can be done to overwrite it.