Clay Banks
Clay Banks

Reputation: 4581

How to Update All Fields Submitted in a Form - Spring MVC

I have a form that has 10+ field inputs that will get updated by a user. On submit I need to update the object (by id) and any/all fields that were modified in the form (utilizing Spring Data JPA & Repositories). I believe I can do this by passing the @ModelAttribute as a method argument tied to my object, but I don't quite fully understand this yet. Here's my Controller

    @RequestMapping(value = "/saveUser/{id}", method = RequestMethod.POST)
    public String saveUser(@ModelAttribute("User") User user, @PathVariable Long id, Model model) {
        user = userRepo.findOne(id); //Spring Repository method to find user by ID  
        // Here is where you'd set all fields of the User object including those modified in the form
        model.addAttribute("user", user);
        userRepo.save(user); //Updates user in database
        return "success";
    }

I'm looking for a method that would do the exact same thing as:

user.setName(user.getName());
user.setAddress(user.getAddress));
//etc.

Without explicitly calling each set method (the number of field inputs will grow).

Thanks mates

Upvotes: 2

Views: 3415

Answers (1)

paul
paul

Reputation: 13471

If you have a form and you´re using ModelAndAttribute you just need to set the id attribute to be send to the Controller

  <form:input id="id" path="id"/>
                <form:input id="name" path="name"/>
                <form:input id="address" path="address"/>

Then in your controller you just need to do what you´re just doing

   @RequestMapping(value = "/saveUser/{id}", method = RequestMethod.POST)
public String saveUser(@ModelAttribute("User") User user, @PathVariable Long id, Model model) {
    user = userRepo.findOne(id); //Spring Repository method to find user by ID  
    // Here is where you'd set all fields of the User object including those modified in the form
    model.addAttribute("user", user);
    userRepo.save(user); //Updates user in database
    return "success";
}

BUT, if you´re doing this request by Ajax you will need to load the again the entity User to set the new entity in your form with the new Id. You can take a look to JQuery load to load the form element again.

Or if the save is done by HTTP Request you must refresh the page after save so you need to return again the ModelAndView with the entity user already update with an id

    @RequestMapping(value = "/saveUser/{id}", method =                 RequestMethod.POST)
    public String saveUser(@ModelAttribute("User") User user,         @PathVariable Long id, Model model) {
        user = userRepo.findOne(id); //Spring Repository method to find user by ID  
        userRepo.save(user); //Updates user in database
        ModelAndView mav = new ModelAndView(yourview);
        mav.setObject("user", user);
        return mav;
     }  

Upvotes: 1

Related Questions