2012-01-25 46 views
0

我試圖編輯實體列表並在之後更新或創建它們。 在我的控制,我有:如何映射用於編輯和保存的對象列表

public static void editTargets(@Required @Min(2011) Integer year, @Required String type, @Required Long groupId) { 
    RetailRegion region = RetailRegion.findById(groupId); 
    notFoundIfNull(region); 
    TargetType tType = TargetType.valueOf(type); 
    notFoundIfNull(tType); 

    List<Target> targets = Target.findByGroupAndTypeAndYear(region, tType, year); 

    if (targets != null && !targets.isEmpty()) { 
     render(targets, year, tType, region); 
    } 
    createTargets(year, type, groupId); 
} 

public static void createTargets(@Required @Min(2011) Integer year, @Required String type, @Required Long groupId) { 
    RetailRegion region = RetailRegion.findById(groupId); 
    notFoundIfNull(region); 
    TargetType tType = TargetType.valueOf(type); 
    notFoundIfNull(tType); 

    render(region, year, tType); 
} 

public static void saveTargets(@Required List<Target> targets) { 
    notFoundIfNull(targets); 

    for (Target target : targets) { 
     if (target != null) 
      target.save(); 
    } 

    flash.success("Targets have been saved."); 
    if (params.get("_save") != null) { 
     mgmt(); 
    } 
    mgmt(); 
} 

和我editTargets模板:

#{form id:'targetsForm', method:'POST', action:@saveTargets()} 
    <section id="targets"> 
    <table width="750px" id="targetsTable"> 
     <thead> 
     <tr> 
     <th>Code</th> 
     <th>January</th> 
     </tr> 
     </thead> 
     <tbody> 
     %{int i = 0;}% 
     #{list items:targets, as:'target'} 
     <tr> 
      #{field 'target.id'} 
      <input id="${field.id}" type="hidden" name="${field.name}" value="${field.value}" class="${field.errorClass}" /> 
      #{/field} 
      <td class="center">${targets[i].code}</td> 
      <td class="center"> 
      #{field 'target.jan'} 
      <input id="${field.id}" type="number" name="${field.name}" value="${field.value}" class="${field.errorClass}" /> 
      #{/field} 
      </td> 
      ... 

我的問題是,我似乎並沒有能夠映射回所編輯的目標在saveTargets控制器方法。

控制器會將字段映射回每個字段的字符串數組(即target.jan - > String []),而不是列表<Targets>。

有沒有辦法將我的對象映射回列表?

回答

1

您好像在循環瀏覽視圖中的目標,因此您的字段標記應包含它們在列表/數組中的事實。有趣的是,target.jan雖然作爲一個字符串數組以某種方式來了。我覺得你的領域標記看起來應該是這樣的:

%{ fieldName = "target[${i}].jan" }% 
#{field "${fieldName}"} 
    ... 
#{/field} 

以上是針對「一月」屬性,所以你必須爲你的觀點有任何其他的目標屬性做同樣的(比如:id )

+0

我現在正在做一些與#{list items:targets,'target'}近似工作的東西「} emt14

+0

我說近乎工作,因爲這些字段在目標列表中正確映射。出於某種原因,只有id沒有被映射,這是一種煩人的,因爲這是更新模型的關鍵。任何想法? – emt14

+0

您是否使用我在答案中提供的代碼嘗試它?如果是這樣,那麼發生了什麼? – digiarnie