views:

458

answers:

1

I'm trying to create a a custom constraint. I've put the logic in a service:

class RegExpManagerService {

    boolean transactional = false
    def messageSource

    def lookupRegexp(regExpression,Locale locale) {

       def pattern = messageSource.getMessage( regExpression,null,locale )
       return pattern
    }

    def testRegexp(regExpression,text,Locale locale) {
       return text ==~ lookupRegexp(regExpression,locale)
    }
}

and tried to inject it in my domain controller:

class Tag extends IbidemBaseDomain {

    def regExpManagerService
    static hasMany=[itemTags:ItemTag]
    static mapping = {
        itemTags fetch:"join"
    }

    //Long id
    Date dateCreated
    Date lastUpdated
    String tag
    // Relation
    Tagtype tagtype
    // Relation
    Customer customer
    // Relation
    Person updatedByPerson
    // Relation
    Person createdByPerson

    static constraints = {
        dateCreated(nullable: true)
        lastUpdated(nullable: true)
        tag(blank: false,validator: {val,obj ->
                regExpManagerService.testRegexp(obj.tagtype.regexpression,val,local)
        })
        tagtype(nullable: true)
        customer(nullable: true)
        updatedByPerson(nullable: true)
        createdByPerson(nullable: true)
    }
    String toString() {
        return "${tag}" 
    }
}

When the constraint gets executed I get this error:

2009-08-24 18:50:53,562 [http-8080-1] ERROR errors.GrailsExceptionResolver  - groovy.lang.MissingPropertyException: No such property: regExpManagerService for class: org.maflt.ibidem.Tag
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingPropertyException: No such property: regExpManagerService for class: org.maflt.ibidem.Tag
+3  A: 

The constraints closure is static, so it can't see the instance field 'regExpManagerService'. But you have the object being validated so you can access it from that:

   tag(blank: false,validator: {val,obj ->
      obj.regExpManagerService.testRegexp(obj.tagtype.regexpression,val,local)
   })
Burt Beckwith
That did it. Now I just have to figure out how to get the locale...
Brad Rhoads