简体   繁体   中英

Grails: how to set a meta-constraint on domain class property?

I have a Contact class that belongs to a Subscription and I want to set a hypothetic readonly constraint on the subscription property, to be consumed in the scaffold templates.

The class looks like

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
}

I found ConstrainedProperty.addMetaConstraint method that "adds a meta constraints which is a non-validating informational constraint".

How do I call it from within the Domain class?

And how do I get the meta-constraint?

In the scaffolding templates there is a property domainClass from type org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass. These object has the property constrainedProperties. To have excess to the 'readonly' you have to do this:

Your domain class:

class Contact {
   static belongsTo = [subscription: Subscription]

   static constraints = {
       subscription(nullable: false, attributes: [readonly: true])  
   }

   String description
}

in the scaffolding template:

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

the DefaultGrailsDomainClass has a constructor with a attribute from type Class maybe you can do this:

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

Maybe there is a Factory for this, but I don't know.

If you specifically want a readonly constraint that influences the scaffolded form fields, you can use:

static constraints = {
    subscription(editable: false)
}

Here's a list of the constraints that are used by renderEditor.template (that I could find with a quick search, anyway):

  • editable (if false , causes rendered field to be readonly - works for String and Date fields)
  • widget (if 'textarea', field is rendered as a textarea - works for String fields)
  • format (for date fields, supplies the constraint value to the datePicker's format attribute)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM