2011-04-27 63 views
0

我有一個圖是這樣的:僅將某些屬性綁定到grails域對象上?

['var1':'property1', 'var2':'3']

和一類這樣的:

class MyClass{ 
    MyEnum var1 
    int var2 
    String var3 
} 
enum MyEnum{ 
    PROP1("property1") 
    PROP2("property2"); 

    private final String variable; 

    public MyEnum(String variable){ this.variable = variable } 
    public String getVariable(){ return variable } 
} 

我想只是嘗試綁定var1var2到一些現有的對象來獲取驗證,但我該怎麼做?

回答

6

您可以使用bindData控制器內。此方法具有可選參數,可讓您明確指出綁定應包含或排除哪些屬性,例如,

def map = ['var1':'property1', 'var2':'3'] 
def target = new MyClass() 

// using inclusive map 
bindData(target, map, [include:['var1', 'var2']]) 

// using exclusive map 
bindData(target, this.params, [exclude:['var2']]) 

如果你想要做這樣的一個控制器外結合使用的org.codehaus.groovy.grails.web.binding.DataBindingUtils的方法之一,例如

/** 
* Binds the given source object to the given target object performing type conversion if necessary 
* 
* @param object The object to bind to 
* @param source The source object 
* @param include The list of properties to include 
* @param exclude The list of properties to exclud 
* @param filter The prefix to filter by 
* 
* @return A BindingResult or null if it wasn't successful 
*/ 
public static BindingResult bindObjectToInstance(Object object, Object source, List include, List exclude, String filter) 

下面是使用此方法來執行相同的結合作爲bindData上述

def map = ['var1':'property1', 'var2':'3'] 
def target = new MyClass() 
DataBindingUtils.bindObjectToInstance(target, map, ['var1', 'var2'], [], null) 
+0

一個巨大的警告:如果分別綁定父對象和容器對象,容器對象上產生的錯誤不會得到波及到父母。 – 2011-04-28 17:22:17

1

對此可以使用bindData方法,因此您可以指定要綁定哪些屬性或哪些不需要綁定。

+0

我可以在控制器外部進行此操作嗎? – 2011-04-27 18:18:35

+0

我只在控制器內部使用過它,但是如果你需要的話,你可能想要檢查DataBindingUtils和BindDynamicMethod類,這些類可以完成與bindData方法有關的所有事情,並查看是否可以在控制器外部使用bindData。不確定是否有已經內置的解決方案或更容易的情況下。 – Maricel 2011-04-27 20:04:12

0

您也可以嘗試

Map myClassMap = ['var1':'property1', 'var2':'3'] 
//You can use either of the following options 
MyClass myClass = new MyClass(myClassMap) 
myClass.properties = myClassMap 
+0

這些選項僅適用於GORM對象。一個POGO沒有一個構造函數需要一個'Map'或一個'setProperties(Map map)'方法 – 2011-04-28 09:37:10

0

還可以使用以下語法「包容地圖」調用的一個例子:

// update the var1 and var2 properties in the target 
target.properties['var1', 'var2'] = params 

中所述代碼4Secure Data Binding With Grails