是否有办法根据用户点击的控制器操作强制使用域字段?
示例:
class Color {
String name
String shade
static constraints{
name nullable: true, blank: true
shade nullable: true, blank: true
}
}
class MyController {
def save1() {
//here I want only name field to be required
Color c = new Color(params)
c.save()
}
def save2() {
//here I want only shade field to be required
Color c = new Color(params)
c.save()
}
}
答案 0 :(得分:3)
你有一个选择是这样的:
class MyController {
def save1() {
//here I want only name field to be required
def color = new Color(params)
if(color.validate(['name'])) {
color.save(validate: false)
}
}
def save2() {
//here I want only shade field to be required
def color = new Color(params)
if(color.validate(['shade'])) {
color.save(validate: false)
}
}
}
答案 1 :(得分:0)
您可以使用CommandObject
并在那里定义自己的约束
请参阅http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects
e.g:
@grails.validation.Validateable
class ColorWithName {
String name
String shade
static constraints = {
name(nullable: false, blank: false)
}
}
class ColorController {
def save1(ColorWithName color) {
if (color.hasErrors()) { ...