0

Basically I have a Form which I have an Object 'Sighting' being made, when being requesting the specific URL to make a sighting. Although, In the form I have another object Which I would like in a tag to be populated from a database. This select tag basically gets all the 'pests' from a database and populates them. My controller is setting adding 2 attributes like this, I am not sure if it is the correct way of doing it, or will one object overwrite another when submitting it.

My Controller Method:

@RequestMapping("/sighting")
public String makeSighting(Model model, Principal principal) {

    List<Pest> pests = pestsService.getPests();
    model.addAttribute("pests", pests);
    model.addAttribute("sighting", new Sighting());

    return "sighting";
}

If you could help me out that would be great. If needed I will provide the code for the Form also. Thanks

1 Answer 1

1

There is nothing wrong with this approach. But you can define a single form backing object for your form:

class SightingForm {
Sighting sighting;
List<Pest> pests;
...
}

And this can be used to populate the form :

@RequestMapping("/sighting")
public String makeSighting(Model model, Principal principal) {

    List<Pest> pests = pestsService.getPests();
    SightingForm sightingForm = new SightingForm();
    sightingForm.setSighting(new Sighting());
    sightingForm.setPests(pests);

    model.addAttribute("sightingForm", sightingForm);

    return "sighting";
}

and in your JSP, use this single sightingForm as your form backing object:

<form:form id="form" action="${submitUrl}" modelAttribute="sightingForm" method="POST">
<form:input path="property" id="propertyId" />
...
</form:form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.