Grails 如何根据控制器操作使域的字段成为必填字段?
是否有一种方法使域字段成为必填字段,具体取决于用户执行的控制器操作 例如:Grails 如何根据控制器操作使域的字段成为必填字段?,grails,groovy,Grails,Groovy,是否有一种方法使域字段成为必填字段,具体取决于用户执行的控制器操作 例如: 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 na
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()
}
}
您有这样一个选择:
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)
}
}
}
您可以使用
CommandObject
并在那里定义自己的约束
看
e、 g:
这是可行的,但请注意,这将为要在不同场景中应用的每个验证组合编写一个新的命令对象类,并且在对实际域类调用
.save()
时,仍必须关闭验证。
@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()) { ...