Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails checkbox

Tags:

grails

I have trouble with binding Boolean property in association classes. Property is set to true if I check checkbox (good), but is null if checbox is not checked.

I know the problem with HTML checkbox. I know why is send "_fieldName" in params, but this "_fieldName" dont set my boolean property to false.

class Person{
   String title

   List<Group> groups = new ArrayList()
   static hasMany = [groups: Groups]    
}

class Group{
   String title
   Boolean isHidden

   static belongTo = Person
}

class PersonController{

   def form = {
      def person = new Person()
      person.groups.add( new Group() )    
      return ["person": person]
   }

   def handleForm = {
      def person = new Person( params )
      println person.groups[0]
   }
}


 <g:form action="save">
    <g:textField name="title" value="${person?.title}" />
    <g:textField name="groups[0].title" value="${person?.groups[0]?.title}"/> 
    <g:checkBox name="groups[0].isHidden" value="${person?.groups[0]?.isHidden}"  />   
    <g:submitButton name="save" value="Save" />
  </g:form>

If I check checkbox:
[isHidden:on, title:a, _isHidden:]
println person.groups[0] //true

If I don check checkbox:
[title:a, _isHidden:]
println person.groups[0] //null



Thank a lot for help
Tom
I am sorry, I searched this web, but did not get actual info for my trouble.

like image 697
Tomáš Avatar asked May 30 '10 06:05

Tomáš


3 Answers

After much hacking it appears the answer is that grails is looking for a marker field with the name:

groups[0]._isHidden

rather than

_groups[0].isHidden

which is actually what the g:checkBox tag generates. See GrailsDataBinder.java:911 see propertyStartsWithFieldMarkerPrefix(PropertyValue pv, String fieldMarkerPrefix) for confirmation

If you are interested I've uploaded the test project for this question to gitub.com

like image 135
Gareth Davis Avatar answered Oct 15 '22 08:10

Gareth Davis


I correct checkbox tag. Thanks to gid help, now it work with association too.

from source:
http://grails.org/doc/latest/ref/Tags/checkBox.html#

 if (value == null) value = false

out << "<input type=\"hidden\" name=\"_${name}\" /><input type=\"checkbox\" name=\"${name}\" "

if (value && checked) { out << 'checked="checked" ' } 

to:

if (value == null) value = false

def begin =  name.lastIndexOf('.') +1
def tail =  name.substring( begin);
out << "<input type=\"hidden\" name=\"${name.replace(  tail, "_" + tail  )}\" /><input type=\"checkbox\" name=\"${name}\" "

if (value && checked) { out << 'checked="checked" ' } 
like image 37
Tomáš Avatar answered Oct 15 '22 08:10

Tomáš


Use the code below,

<g:checkBox name="checkbox" value="HELLO" />

Refer :

  1. http://grails.asia/grails-checkbox-tag-example/
  2. http://grails.org/doc/latest/ref/Tags/checkBox.html
like image 1
Prabhat Kashyap Avatar answered Oct 15 '22 07:10

Prabhat Kashyap