Search code examples
javaspringformshibernatemodelattribute

How to get modelAttribute values that are not in form, in Spring


I have an hibernate entity object. I need to update this object, so I passed this object to a form. In the form i will change some values and the others are constant. And I can not show these constant values to the client, so they should pass to next page via another method except from diplaying them explicity in a html form.

Here is my object obtained in controller and passed to the view:

@GetMapping("/update")
public String update(@RequestParam("dataId") int id, Model md){
    Doctor dr = doctorService.getById(id);


    /*for example lets say this doctor object has following properties
    dr.setId(3);
    dr.setName("James");
    dr.setUserId(7);
     */

    md.addAttribute("doctor", dr);


    return "object-form";
}

Here is my form in view :

<form:form action="save" modelAttribute="doctor" method="post">

    <form:errors path="name"></form:errors>
    <form:input path="name" placeholder="Doktor İsmi" class="form-control" />

    <form:hidden path="id" />
    <input type="submit" value="Save doc" />
</form:form>

From form, only name and id values are coming, however, the userId is null. I need to get this userId without post.

Here is my post-process controller that I handle the object:

@PostMapping(value="/save")
public String save(@Valid Doctor dr,  BindingResult bindingResult){

    doctorValidator.validate(dr, bindingResult);
    if (bindingResult.hasErrors()) {
        return "object-form";
    }
    else{
        doctorService.save(dr);
        return "redirect:list";
    }
}

I don't know how can achieve this r even there is way for it. I searched on Google but I did not find any solution.

Thank a lot,,


Solution

  • You can get previous doctor object from db and get the user ID from there like below:

    @PostMapping(value="/save")
    public String save(@Valid Doctor dr,  BindingResult bindingResult){
        Doctor prevDr = doctorService.getById(dr.getId());
        dr.setUserId(prevDr.getUserId());
        doctorValidator.validate(dr, bindingResult);
        if (bindingResult.hasErrors()) {
            return "object-form";
        }
        else{
            doctorService.save(dr);
            return "redirect:list";
        }
    }