2012-05-31 32 views
2

在我的應用程序中,許多類具有公共字段「公司」。當應用程序保存該對象時,它們必須由公司填充(對此有驗證)。公司也被保留在會議中。現在,當我想使用域類作爲命令對象時,公司必須已經被填充或者出現驗證錯誤。在驗證發生之前,是否有任何方法可以始終填寫公司字段,以便我不必每次都手動完成。 (我試過定製數據綁定,但是當有一個請求,沒有參數它不工作)Grails,使用會話中的值注入/填充域對象

回答

1

您可以設置該屬性之前的對象被保存,更新,或使用GORM eventsbeforeInsertbeforeUpdatebeforeValidate驗證。

在您的域名,你需要類似的東西:

import org.springframework.web.context.request.RequestContextHolder 
class Foo { 
    String company 
    ... 
    def beforeInsert = { 
     try { 
      // add some more error checking (i.e. if there is is no request) 
      def session = RequestContextHolder.currentRequestAttributes().getSession() 
      if(session) { 
       this.company = session.company 
      }    
     } catch(Exception e) { 
      log.error e 
     } 
    } 
} 
+0

beforeValidate - 這正是我需要的,謝謝 –

1

如果你想前財產綁定的結合過程中,您可以創建自定義BindEventListener並在的Grails應用程序內註冊/的conf /春/ resources.groovy

首先,創建自定義BindEventListener

/src/groovy/SessionBinderEventListener.groovy

import org.springframework.beans.MutablePropertyValues 
import org.springframework.beans.TypeConverter 

class SessionBinderEventListener implements BindEVentListener { 

    void doBind(Object wrapper, MutablePropertyValues mpv, TypeConverter converter) { 
     def session = RequestContextHolder.currentRequestAttributes().getSession() 
     mpv.addPropertyValue("company", session.company) 
    } 

} 

所有的二,註冊您的BindEventListener

的grails-app/conf目錄/春/ resources.groovy

beans = { 
    sessionBinderEventListener(SessionBinderEventListener) 
} 

然而 ,如果您的域名類不包含公司名稱,您將獲得InvalidPropertyException。爲了克服這個問題,創建的其中含有一種叫公司財產類的列表 - 查看詳情婁

/src/groovy/SessionBinderEventListener.groovy

import org.springframework.beans.MutablePropertyValues 
import org.springframework.beans.TypeConverter 

class SessionBinderEventListener implements BindEVentListener { 

    private List<Class> allowedClasses = [Foo] 

    void doBind(Object wrapper, MutablePropertyValues mpv, TypeConverter converter) { 
     if(!(allowedClasses.contains(wrapper.class))) { 
      return 
     } 

     def session = RequestContextHolder.currentRequestAttributes().getSession() 
     mpv.addPropertyValue("company", session.company) 
    } 

} 
相關問題