2014-11-21 110 views
0

我一直在嘗試在Grails項目中創建自定義約束(請參見下面的約束代碼)。自定義Grails約束似乎沒有工作

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; 
    } 
} 

正如你所看到的,這個約束實際上並沒有驗證任何東西。相反,它只是標記來自定義腳手架代中的屬性渲染。 創建上面的類之後,我加在Config.groovy文件以下行:

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

..和添加了這個約束類的屬性:

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

但是,如果我嘗試得到表達式的結果 ThatClass.constraints.someVariable.getAppliedConstraint("busca"), 我得到的全部是null

我基於我的方法在一些博客文章中,如this oneconstraint in Grails' github repo(但我不明白他們是如何配置的)。

我在做什麼錯? 最近Grails的自定義約束配置有變化嗎?

回答

0

看起來你的約束是好的。我在Url Without Scheme Validator Plugin中使用類似UrlWithoutSchemeConstraint的類似的東西,它在最近的Grails(2.3.x,2.4.x)中很有魅力。

但是,我從來沒有嘗試過在運行時訪問它,所以我試圖調查這個區域。例如,你有沒有試過ThatClass.constraints.someProperty.busca

0

我也使用我的約束作爲Grails 2.4.4項目中的標記。約束可以通過以下代碼訪問:

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

其中p.name是屬性名稱,「encodeAsRaw」是我的約束的名稱。我在一些.gsp文件中成功使用了這段代碼。

如果只是用作標籤,甚至不需要創建自定義約束類並註冊它。只需使用getMetaConstraintValue方法檢查它的存在就足夠了。

爲了完整起見,這裏是我的領域類我的約束定義:

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