简体   繁体   中英

Custom Grails Constraint doesn't seem to work

I have been trying to create a custom constraint in a Grails Project (see constraint code below).

import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors

class BuscaConstraint extends AbstractConstraint {

    public static final String CONSTRAINT_NAME = "busca"

    protected void processValidate(Object target, Object propertyValue, Errors errors) {
    }

    boolean supports(Class type) {
      return type && String.class.isAssignableFrom(type);
    }

    String getName() {
      return CONSTRAINT_NAME;
    }
}

As you can see, this constraint doesn't actually validates anything. Instead, it's just a flag to customize the property's rendering in the scaffolding generation. After creating the class above, I added the following line in the file Config.groovy:

ConstrainedProperty.registerNewConstraint(BuscaConstraint.CONSTRAINT_NAME, BuscaConstraint.class)

..and added this constraint to a class's property:

class ThatClass {
  def someProperty
  static constraints = { someProperty (unique:true, busca: "nome") 
}

However, if I try to get the result of the expression ThatClass.constraints.someVariable.getAppliedConstraint("busca") , all I get is null .

I based my approach in some blog posts such as this one and from a constraint in Grails' github repo (however I can't see how they are configured there).

What am I doing wrong? Has the configuration of Grails' custom constraints changed recently?

It looks your constraint is good. I use something very similar in my Url Without Scheme Validator Plugin , in class UrlWithoutSchemeConstraint and it works like a charm in recent Grails (2.3.x, 2.4.x).

However, I never tried to access it at runtime, so I'd try to investigate this area. For example, have you tried ThatClass.constraints.someProperty.busca ?

I am also using my constraint as a tag in a Grails 2.4.4 project. The constraint can be accessed with the following code:

domainClass.constraints[p.name].getMetaConstraintValue("encodeAsRaw")

Where p.name is the property name and "encodeAsRaw" is the name of my constraint. I am using this code successfully in a couple of .gsp files.

If just using as a tag, you don't even need to create a custom constraint class and register it. It's enough just to check for its existence with the getMetaConstraintValue method.

For completeness, here is my constraint definition in my domain class:

myProperty(nullable:true, blank:true, unique:false, maxSize:1000, encodeAsRaw:true)

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