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
?