开发者

Grails checkbox

I have trouble with binding Boolean property in association cl开发者_高级运维asses. 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.


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


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" ' } 


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


Set the default value of the check-box to "false", and it should solve the issue. Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜