【问题标题】:Grails 3 Accessing Grails domain constraints at runtimeGrails 3 在运行时访问 Grails 域约束
【发布时间】:2015-09-17 09:29:42
【问题描述】:

我曾经像这样在我的 gsp 中访问 grails 2 约束:

${MyDomainClass.constraints.myProperty.inList.collect{it.name()}} 

它不再在 Grails 3 中工作

【问题讨论】:

  • 好的,这将是 grailsApplication.getArtefact('Domain', 'MyDomainClass').getConstrainedProperties().myProperty.inList.collect{it.name()}
  • 您应该将您的评论放在答案中,并附上支持差异的 Grails 文档的链接。这样未来的读者就可以轻松找到这个答案。

标签: grails grails-orm grails-3.0


【解决方案1】:

在 Grails 3.0 中,域和命令对象使用 trait grails.validation.Validateable (可以找到源代码 here。通过提供以下方法,该特征使您可以访问约束。

static Map<String, ConstrainedProperty> getConstraintsMap();

为了访问您在域或命令对象上调用该方法的约束。以下示例访问名为 day 的域对象属性上的 nullable 约束。

domainObject.getConstraintsMap()['day']['nullable']

【讨论】:

  • 所以据我了解,对于域类,根据 DomainClass 特征,它将是 static Map&lt;String, Constrained&gt; getConstrainedProperties();(source)domainObject.getConstrainedProperties()['day']['nullable']Validateable trait 用于命令对象。
【解决方案2】:

这种方式在 Grails 2 中有效,现在仍然有效...

grailsApplication.getArtefact('Domain',
    'MyDomainClass').getConstrainedProperties().myProperty.inList.collect{it.name()}

see GrailsDomainClass API

【讨论】:

  • 实际上在 Grails 3 中通过引入特征改变了访问权限。
猜你喜欢
  • 2015-10-20
  • 2015-11-09
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多