Showing posts with label constrainedProperties. Show all posts
Showing posts with label constrainedProperties. Show all posts

Friday, October 25, 2013

Grails GORM constrained properties: check if a domain attributes properties mapping

Consider a grails domain class like below:



package com.pritom.domains.customer

class Customer {
    Integer id;
    String customerId
    String email;
    String password
    Date dateCreated = new Date()
    Date lastUpdated = new Date()

    static mapping = {

    }

    static constraints = {
        customerId unique: true
        email unique: true
        creditCard(nullable: true);
    }
}

Now get domain class constrained properties:



def domainClass = new DefaultGrailsDomainClass(com.pritom.domains.Customer)
def constrainedProperties = domainClass.constrainedProperties;

Now check if specific field has some specific property



String key = "customerId";

if (constrainedProperties.containsKey(key)) {
    ConstrainedProperty v = (ConstrainedProperty) constrainedProperties.get(key);
    if(v.isNullable()) println 'Nullable';
    if(v.isBlank()) println 'Blank';
    if(v.isCreditCard()) println 'Credit Card';
    if(v.isDisplay()) println 'Display';
    if(v.isEditable()) println 'Editable';
    if(v.isEmail()) println 'Email';
}


And you can check more properties as you wish.

http://pritomkumar.blogspot.com/2013/09/javagrails-class-constrainedproperty.html

Monday, September 30, 2013

Grails: how to get/set a meta-constraint on domain class property such as belongsTo or other variables

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 access to any properties such in this example: '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
}


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



def domainClass = new DefaultGrailsDomainClass(it.metaClass.getTheClass())
def constrainedProperties = domainClass.constrainedProperties;
if(constrainedProperties.containsKey("subscription")) {
    ConstrainedProperty v = (ConstrainedProperty) constrainedProperties.get("subscription");
    /**
     * Now check
     */
    if(v.isNullable()) {
        println "Nullable";
    }
    if(v.isBlank()) {
        println "Blank";
    }
    /**
     * There are may other constraints
     * http://grails.org/doc/latest/api/org/codehaus/groovy/grails/validation/ConstrainedProperty.html 
     * Java/Grails Class ConstrainedProperty
     */ 
 }