2013-07-04 87 views
0

我使用Hibernate驗證與Spring MVC和我有一個問題與多選(在ManyToMany關係)。我的基類是Project。項目有(其中包括)字段:姓名(字符串),用戶(多對一),區(多對多)Autopopulate多選與Hibernate驗證

class Project { 
    . 
    private String name; 
    private User user; 
    private List<Region> regions 
    . 
} 

在控制器(POST行爲),我有:

public String saveProject(
    @Valid Project project, 
    BindingResult bindingResult, 
    ModelMap model) { 

    //send regions, users etc. to model 

    //errors 
    if(bindingResult.hasErrors()) { 

     System.out.println(project.getRegions().size()); 
     //Printed size of regions is identical with selected 

     return "templates/project/form";   
    } 


    //no errors, save to database etc. 

} 

InitBinder:

@InitBinder 
public void initBinder (WebDataBinder binder) 
{ 
    StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true); 
    binder.registerCustomEditor(String.class, stringtrimmer); 

    binder.registerCustomEditor(List.class, "regions",new CustomCollectionEditor(List.class){ 
     @Override 
     protected Object convertElement(Object element) { 
      Region region = new Region(); 

      if (element != null) { 
       Integer id = Integer.valueOf(element.toString()); 
       region.setId(id); 
      } 
      return region; 
     } 
    }); 

在回報表格中,字段'name'id填寫完畢,用戶被選中,但區域多選是

更有趣的是,如果對象仍然存在於數據庫中,那麼在'編輯'表單中,多選是正確填寫

回答

0

一個我找到了解決辦法是加載區的完整的對象是「saveProject」行動:

if(bindingResult.hasErrors()) { 

    System.out.println(project.getRegions().size()); 
    //Printed size of regions is identical with selected 

    if (project.getRegions() != null) { 
     List<Region> regionsTemp = new ArrayList<Region>(); 
     for (Region region1 : project.getRegions()) { 
      Region region = Database.findById(region1.getId()); 
      regionsTemp.add(region); 
     } 
     project.setRegions(regionsTemp); 
    } 

    return "templates/project/form";   
} 

任何其他的想法?