Problem: getting an object from a field as a parameter.
Code: Entity User with fields:
Long id;
String name;
Office office;
Entity office with fields:
Long id;
String name;
newuser.vm
<title>NEW USER</title>
<body>
<form method="post" action="/save" property="user">
Name:
<input type="text" name="name" path="name"/> <br>
Office:
<select name="office" path="office">
#foreach($office in $offices)
<option value="$office">$office.name</option>
#end
</select> <br>
<input type="submit" value="SAVE"/>
</form>
</body>
And the Controller
@Controller
public class ViewController {
@Autowired
private UserService userService;
@Autowired
private OfficeService officeService;
@RequestMapping(value = "/newuser", method = RequestMethod.GET)
public ModelAndView newuser(){
return new ModelAndView("fragments/newuser.vm","command",new User());
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("user") User user){
userService.create(user);
return new ModelAndView("redirect:/list");
}
//Model Attributes
@ModelAttribute
public void userTypesList(Model model){
model.addAttribute("types", userService.getPositions());
}
@ModelAttribute
public void officesList(Model model){
model.addAttribute("offices", officeService.getAll();
}
So in the result of submition I have to get the new User with an Office as one of its fields. But the <option value="$office">$office.name</option>
returns a string representation of the object but not the object itself i guess. So i need to find a way to correctly get that to the /save controller. Ofcourse I can get field by field data from the form and create a new user manualy getting the office.id from the form and than sending another request to sql to get the officeById(id), but that seems to be the bad way of coding. Anyone can help?
What you need is:
<option value="$office.id">$office.name</option>
That's what id fields are for. Only the office id get transmitted back when the form is submitted, and that's all you need to populate the join towards the office table while creating your new user.
To have $office
display the string representation of the whole object (that is, its toString()
method) is the expected behavior.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments