How can I declare inList constraints from a controller in Grails?

若如初见. 提交于 2019-12-24 00:48:37

问题


Can anyone show me how to declare an inList constraint within a Grails controller?

Let’s say I have this class:

class A {
    List hello
}

How can I add the inList constraint for the hello List from within the controller?


回答1:


Define a constraint in which a List property has values validated against a list of lists? Sounds weird. But you can do it. With this class:

class A {
    List hello
    static constraint = {
        hello inList:[['abc','def','ghi'],[1,2,3],['a','b']]
    }
}

you can do this in your controller:

def instance1 = new A(hello:['abc','def','ghi']).save()    //valid
def instance2 = new A(hello:[1,2,3]).save()                //valid
def instance3 = new A(hello:['a','b']).save()              //valid
def instance4 = new A(hello:['a','b','c']).save()    //invalid
def instance5 = new A(hello:[1,2]).save()            //invalid

If A is a domain class whose instances are persisted in a traditional database, however, the hello property would be dropped, so you’d need to define it using

static hasMany = [hello: SomeClass]

instead.




回答2:


You can write a custom validator to your fields that check if data are in List. You will have to implement the in list checking manually. You can find here the official documentation. There are some stackoverflow entries that can help you like

Grails: Custom validator based on a previous value of the field



来源:https://stackoverflow.com/questions/14272680/how-can-i-declare-inlist-constraints-from-a-controller-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!