Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - Set "disabled" attribute name and value in GSP

I´m trying to do this without success:

<g:textField title="${title}" ${disabled} />

I want to apply a disabled attribute, ONLY if the ${disabled} variable is TRUE. I don't want to use conditionals, because in other views I got a lot of code and using IF statements, will be a chaos.

The other thing is applying the attribute like this:

<g:textField title="${title}" disabled="${disabled}" />

But when I put the disabled attribute, no mather the content of the variable, It just always disables the field.

like image 361
David Morabito Avatar asked May 19 '11 16:05

David Morabito


2 Answers

if you don't like gotomanners' solution (which seems perfectly valid to me)

<g:textField title="${title}" ${(disabled)?"disabled":""} />
like image 173
Grooveek Avatar answered Oct 04 '22 20:10

Grooveek


your ${disabled} variable should be returning "disabled" not TRUE for that to work.

EDIT

I tried this out and saw the problem with it always being disabled no matter the value. Apparently the mere presence of the disabled keyword disables the field and the value assigned to that keyword is only a dummy value.

Anyway, Here's a fix.

  • Create a Taglib class(if you don't have one already)
  • define your own textfield tag as such...

    def myTextField = { attrs, body ->
      def title = attrs.remove("title")
      def isDisabled = attrs.remove("disabled")
    
      if ("true".equals(isDisabled)) {
        out << """<input title="${title}" disabled="${isDisabled}" """
        attrs.each { k,v ->
            out << k << "=\"" << v << "\" "
          }
        out << "/>"
      } else {
        out << """<input title="${title}" """
        attrs.each { k,v ->
            out << k << "=\"" << v << "\" "
          }
        out << "/>" 
      }
    }
    
  • in your gsp, call your textfield tag like so

    <g:myTextField title="${title}" disabled="${disabled}" />
    
  • adding extra attributes like so is also valid

    <g:myTextField class="title" name="theName" value="theValue" title="${title}" disabled="${disabled}" />
    
  • make sure your ${disabled} variable returns "true" or "false" as strings this time.

like image 26
gotomanners Avatar answered Oct 04 '22 21:10

gotomanners