我正在尝试在运行时动态填充static constraint ={}
。有没有办法做到这一点。示例代码:
正常陈述:
static constraint = {
lastName(blank:false, maxSize: 100)
}
我正在尝试做的是:
static constraint = {
call to an XMLSlurper that returns a HashMap of lastName as a key and (blank: false, maxSize: 100) as a value. // This part works.
have the HashMap executed as if it where hard coded information to validate the fields. //This part does not work.
}
我希望这足以解释我的问题。
最佳答案
这是可能的,但是您尝试执行此操作的方式却不可行。使用GrailsHibernateDomainClass加载GORM类的约束。加载该类时,将评估validateConstraints方法和静态属性约束。您可以查看GrailsDomainConfigurationUtil中的validateConstraints方法,以了解如何对其进行评估。
如果要从其他来源添加自己的约束,则需要自行修改域类。最好的方法是在插件中。首先阅读plugin documentation,您的入口点是doWithSpring方法:
def doWithSpring { ->
application.getArtefacts(DomainClassArtefactHandler.TYPE).each { domainClass ->
def myConstraints = getConstraintsFromXml() /* Create a Map<ConstrainedProperty> from your XML */
domainClass.constrainedProperties.putAll myConstraints
}
}
关于xml - 在Grails中使用XML进行动态约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3181416/