开发者

How to ensure a boolean field to be set in Grails?

开发者 https://www.devze.com 2023-01-25 23:34 出处:网络
I want to ensure that one of two form fields representing a boolean value is checked. But there is no appropriate constraint to do this. nullable: false does not work.

I want to ensure that one of two form fields representing a boolean value is checked. But there is no appropriate constraint to do this. nullable: false does not work.

class Organisation {

    Boolean selfInspecting

    static constraints = {
        selfInspecting开发者_Go百科(nullable: false)
    }

}

How can I check whether one of the two fields is checked or not?


Perhaps the simplest approach is to use a form that ensures a value is picked. As such, creating a radio buttons rather than checkboxes is a better solution. It would directly represent your intent as well.


You can also check this in the Controller, e.g.

if (params.checkBox1 != 'on' && params.checkBox2 != 'on')
  flash.error = 'At least one value must be checked.'
  return ...


you can write your own custom validator.

something like

selfInspecting(validator: {val, obj -> /*test selfInspecting here*/})

EDIT -- in response to the other answer -- you can handle this on the form, but you should also handle it on the server.

ANOTHER EDIT -- It was suggested in a comment that you might want to validate one of two fields on your Domain class. This is also easily accomplished with a custom validator. With the signature above for the custom validator closure, the val is the value selfInspecting, and obj is the domain object instance. So you could have

{ val, obj ->

    if (val == null) return false // if you want to ensure selfInspecting is not null
    else return true

    ... or ...

    // if you want to check that at least 1 of two fields is not null
    def oneOrTheOther = false
    if (obj.field1 != null || obj.field2 != null) 
       oneOrTheOther = true
    return oneOrTheOther

}
0

精彩评论

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