2014-09-25 64 views
2

我有一個嵌入對象的grails域類,我只想在更新時驗證嵌入對象的屬性。Grails - 僅在更新時驗證嵌入對象屬性

我知道我可以通過使用自定義驗證程序並檢查域的類ID是否爲空來在普通grails域類上執行此操作。 我不能這樣做,因爲嵌入對象上缺少一個id。

有一個我想要做的例子。

//This is on domain/somePackage/A.groovy 
class A{ 
    B embeddedObject 

    static embedded = ['embeddedObject'] 

    static constraints = { 
     embeddedObject.attribute validator:{val, obj-> //The app fails to start when this code is added!! 
      if(obj.id && !val) //if the id is not null it means the object it's updating... 
       return 'some.error.code' 
     } 
    } 

} 


//this class is on src/groovy/somePackage/B.groovy 
class B{ 
    String attribute 

    static constraints={ 
     attribute validator:{val,obj-> 
      if(obj.id && !val) //This will fail too! because the lack of an id on this object.... 
       return 'some.error.code' 
     } 
    } 
} 

有沒有辦法讓嵌入式對象上的'父'的id? 任何幫助將不勝感激

回答

2

太複雜:

class A{ 
    B embeddedObject 

    static embedded = ['embeddedObject'] 

    static constraints = { 
     embeddedObject validator:{ val, obj -> 
      if(obj.id && !val.attribute) 
       return 'some.error.code' 
     } 
    } 
} 
+0

是的,昨天,嘗試之後我想通了。 – sct999 2014-09-26 15:07:06