D
D
Denis Kuznetsov2019-06-10 05:11:42
Java
Denis Kuznetsov, 2019-06-10 05:11:42

How to handle value in controller from dropdown list?

Hello, on the html page I get the value from the list (plant id)

<form th:action="@{'/plantAdd/'+${boxId}}" method='POST'>
    <table>
        <tr>
            <td>Select plant :</td>
            <td>
                <select name="neededId">
                    <option value=""> -- </option>
                    <option th:each="plant : ${plants}"
                            th:value="${plant.id}"
                            th:utext="${plant.name}">
                    </option>
                </select>

            </td>
        </tr>

        <tr>
            <td><input name="submit" type="submit" value="submit" /></td>
        </tr>
    </table>
</form>

further on this id, I will search in the controller (implement any logic there) there is now a lot left from my previous attempts to get the id
, how can I get it in these controllers?
@RequestMapping(value = "/plantAdd/{boxId}", method = RequestMethod.GET)
    public String plantAdd(Model model,
                           @PathVariable(name = "boxId") Long boxId){

        List<MyPlantNamesExp> listPlantNames = myPlantNameExpDAO.getNames();
        MyPlantNamesExp test = listPlantNames.get(0);
        logger.info("Add method : " + test.toString());

        model.addAttribute("ddForm", new DropDownForm());

        model.addAttribute("plants", listPlantNames);

        return "addPlant";
    }

    @RequestMapping(value = "/plantAdd/{boxId}", method = RequestMethod.POST)
    public String plantAdd(Model model, DropDownForm ddForm,
                           @PathVariable(name = "boxId") Long boxId) throws ResourceNotFoundException {
      //  logger.info("from user action : " + Long.parseLong(ddForm.getPlantName(), 10));
        logger.info("value from request");
        Plant plant = new Plant();
        Long id = Long.parseLong(ddForm.getPlantName(), 10);

        plant.setResponsibleGrowBox(growBoxService.findById(boxId));
        plant.setMyPlantId(myPlantService.findById(id).getId());

        return "addPlant";
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2019-06-10
@DennisKingsman

Hello!
I will write an example code, you already adapt it for yourself.
In the dropdown controller, you can get both the object itself and the object id, and then find this object in the database by ID.
Object lookup by ID option:
You can use Optional to avoid NPE.Optional<Plant>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question