Announcement Announcement Module
Collapse
No announcement yet.
Binding form data using @ModelAttribute Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Binding form data using @ModelAttribute

    Hi,

    As of now, I'm binding more than one datasets to my form using individual forms. For example:
    Code:
    @ModelAttribute("students")
    public Collection<Student> getStudents() {
    	return this.sService.getStudents();
    }
    
    @ModelAttribute("courses")
    public Collection<Course> getCourses() {
    	return this.cService.getCourses();
    }
    
    @ModelAttribute("semesters")
    public Collection<Semester> getSemesters() {
    	return this.sService.getSemesters();
    }
    Is there any way, in which I can define one method such as follows and bind it to the form?

    Code:
    private void setupReferenceData(Model model) {
    	model.addAttribute("students", sService.getStudents());
    	model.addAttribute("courses", cService.getCourses());		
    	model.addAttribute("semester", sService.getSemesters());	
    }
    Thank you.

  • #2
    As of now, I'm able to use setupReferenceData(Model model) from the controller and form is able to get all these lists. However, when the form is submitted with errors I loose all the information and the lists are empty?

    Code:
    @RequestMapping(method = RequestMethod.GET)	
    public String setupNewForm(Model model){
            model.addAttribute("enrollment", new Enrollment());
    	setupReferenceData(model);
    	return "index";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@Valid Enrollment enrollment, BindingResult result, SessionStatus status){
    	if(result.hasErrors()){
    		logger.debug(">>>>There were errors on the form!");
    		return "index";
    	}else
    		enrollService.saveEnrollment(enrollment);
    	return "enroll/success";
    }
    Not sure if this is the right way to set for backing objects!!! May be that's why it is not working as expected.

    Comment

    Working...
    X