【问题标题】:Grails: how to set a meta-constraint on domain class property?Grails:如何在域类属性上设置元约束?
【发布时间】:2011-01-25 14:48:58
【问题描述】:

我有一个属于订阅的联系人类,我想在订阅属性上设置一个假设的只读约束,以便在脚手架模板中使用。

类的样子

class Contact {

   static belongsTo = [subscription: Subscription]

   static constraints = {
     subscription(nullable: false, readonly: true) // hypothetic *readonly* constraint
     name(blank: false)
     email(blank: false, email: true)
   }

   Integer id
   String name
   String email
   String description
}

我发现ConstrainedProperty.addMetaConstraint 方法“添加了一个非验证信息约束的元约束”。

如何在 Domain 类中调用它?

我如何获得元约束?

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    在脚手架模板中有一个来自 org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass 类型的属性 domainClass。这些对象具有属性 constrainedProperties。要超出“只读”,您必须这样做:

    您的域类:

    class Contact {
       static belongsTo = [subscription: Subscription]
    
       static constraints = {
           subscription(nullable: false, attributes: [readonly: true])  
       }
    
       String description
    }
    

    在脚手架模板中:

    def ro = domainClass.constrainedProperties.subscription.attributes.readonly
    

    DefaultGrailsDomainClass 有一个带有 Class 类型属性的构造函数,也许你可以这样做:

    def domainClass = new DefaultGrailsDomainClass(Contact.class)
    def ro = domainClass.constrainedProperties.subscription.attributes.readonly
    

    也许有一个工厂可以解决这个问题,但我不知道。

    【讨论】:

    • 我得到了这个工作,但我必须将约束定义为地图:subscription(attributes: [myConstraint: true])。该约束也可用于renderEditor.template 中使用的cp 实例,例如cp.attributes.myConstraint.
    • 是的,我又尝试了你的几种方法并收到编译错误;我将更新您的答案以使用地图 - 如果我错了,请随时回复。我会给你 +1。
    • @Rob 我的错。上次用javascrip写了很多。
    • 是的,我想知道是不是这样。我发现自己有时也会做同样的事情。
    • 确认它对我有用,并且是我想要的。 +!我很惊讶 addMetaConstraint 没有用例……你知道为什么吗?
    【解决方案2】:

    如果您特别想要一个影响脚手架表单字段的readonly 约束,您可以使用:

    static constraints = {
        subscription(editable: false)
    }
    

    这是renderEditor.template 使用的约束列表(无论如何,我可以通过快速搜索找到):

    • 可编辑(如果false,导致呈现的字段为只读 - 适用于字符串和日期字段)
    • 小部件(如果是“textarea”,则字段呈现为 textarea - 适用于字符串字段)
    • 格式(对于日期字段,将约束值提供给 datePicker 的格式属性)

    【讨论】:

    • 我设法将 oneToMany 属性(在我的示例中为订阅)显示为只读设置 editable:false 约束并调整 renderEditor.tmlpate 以考虑它。我不能添加任意属性:加载域类时没有错误,但我得到一个“groovy.lang.MissingPropertyException:没有这样的属性:类内联:org.codehaus.groovy.grails.validation.ConstrainedProperty " 在 cp.myCustomConstraint 行上的 renderEditor.template 中。
    • @Xan - 你是对的。我不知道为什么我认为这有效,为误导而道歉。出于好奇,我将尝试 Medrod 的答案。我已经删除了答案的后半部分,但会在第一部分保留它。
    • 在那里,我将我的评论下移以恢复订单。看看我对 Merdod 答案的评论 - 他的答案非常接近正确,尽管我不得不对其进行一些修改以使其适合我。
    • 对我来说,在约束中使用 editable: flase 对脚手架 UI 的影响为零 - 它仍然可以编辑。例如“lastLoggedIn nullable: true, editable: false” 仍然允许 lastLoggedIn 是可编辑的,即使我希望它是纯系统生成的(所以只读给用户)。圣杯 2.4.4.
    猜你喜欢
    • 2011-04-25
    • 2014-10-31
    • 2014-12-09
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多