SMash
SMash

Reputation: 345

Populating a drop-down from a database in spring

I am having a jsp page containing a form for add ne item to a system. In there, I need to select the category that the new item belongs to. I need to populate this drop-down list from a database using spring. For the form submission, I am writing a controller class called ItemController.java where the drop-down element is which I need to populate. But, that populating list items need to be called from another controller class named CategoryController.java. I tried so many ways but still I could not able to do it as still getting errors. anybody can have a look on this please?

Here are my codes.

addItem.jsp

  <form:form class="form-horizontal" role="form" id="frmAddItem" action="/admin/items/add_item" method="post" commandName="command">
    <fieldset class="scheduler-border">

    <div class="form-group">
    <div class="row">
    <label for="selectCat" class="col-xs-3 control-label">
       Category
    </label>

    <div class="col-xs-5">

    <form:select class="form-control" id="selectCat" path="categoryName">
    <form:option value="-" label="--Select Category--"/>
    <form:options items="${listCat}" />
    </form:select>
      <span id="catErr" class="input-group-error"></span>
    </div>........

ItemController.java

@Controller
@RequestMapping(value = "/items")
public class ItemController {

    private static final Logger LOG = LogManager.getLogger(ItemController.class);

    @Autowired
    private ItemRepository item;

    @Qualifier("categoryRepository")
    @Autowired
    private CategoryRepository category;

    /**
     * Add new item view
     */

    //For viewing the add item form
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView showAddItem() {
        return new ModelAndView("addItem", "command", new Item());
    }

    //For submitting the add new item
    @RequestMapping(value = "/add_item")
    public String addItem(@ModelAttribute("newItem") Item newItem) throws SQLIntegrityConstraintViolationException {

    System.out.println("First Name:" + newItem.getItemName());

    int a = item.add(newItem);
    if (a == 1)
       return "redirect:add";
       // model.setViewName("addItem");
     else

     // System.out.println("Error in item add");
     return "redirect:add";
     //  return model;
    }

CategoryController.java

@Controller
@RequestMapping("/items")
public class CategoryController {

    private static final Logger LOG = LogManager.getLogger(CategoryController.class);

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ItemRepository item;


    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView showAddItem() {
        ModelAndView model = new ModelAndView();
        List<Map<String, Object>> listCat = categoryRepository.viewCategoryList();
        model.addObject("listCat", listCat);
        return new ModelAndView("addItem", "command", new Item());
    }

Upvotes: 1

Views: 15108

Answers (2)

Clarius
Clarius

Reputation: 1419

I'm working with the Oracle XE sample database. When I update an employee I want to be able to select their manager_id from a list of names. Here's how I did it...

  1. get a list of managers, employees who have subordinates. To achieve this I added a query to the repository. Note - you need to return all the fields to allow the entity to be populated.
    @Query(value="SELECT * FROM employees WHERE employee_id IN (SELECT DISTINCT(manager_id) FROM employees)", nativeQuery=true)
    public List<Employee> findAllManagers();
  1. In the controller I fetched the list of managers and added it to the model.
    @GetMapping("/update")
    public String showFormForUpdate(@RequestParam("employeeId") int employeeId, Model model) {
        
        Employee employee = service.findById(employeeId);
        model.addAttribute("employee", employee);
        
        List<Employee> managers = service.findAllManagers();
        model.addAttribute("managers", managers);
        
        return "employees/form";
    }
  1. In the form I used the list of managers to construct a drop down list.
<select class="form-control" th:field="*{manager.employeeId}" id="managers">
    <option th:each="manager : ${managers}" th:value="${manager.employeeId}" th:text="${manager.lastName} + ', ' + ${manager.firstName}"></option>
</select>

That's what worked for me at time of writing. Luck.

Upvotes: 0

Priyamal
Priyamal

Reputation: 2969

you are trying to add 2 models to the ModelAndView object inside the showAddItem method in CategoryController class, which will not work if you want to add multiple objects to ModelAndView you can use a Map or just use Model class instead.

 @RequestMapping(value = "/add", method = RequestMethod.GET)
 public String showAddItem(Model model) {
    List<Map<String, Object>> listCat =   categoryRepository.viewCategoryList();
    model.addAttribute("listCat",listCat);
    model.addAttribute("command",new Item());
    return "addItem";
 }

since you are trying to populate a dropdown from a List of Maps you might wanna change the current code inside the jsp.

<select name='lists'>  
   <c:forEach var="list" items="${listCat}">
       <option id="${list.key}" value="${list.value.getName()}">${list.value.getName()}</option>   
   </c:forEach>
</select>

change the commandname attribute inside the form too

commandName="command"

Upvotes: 1

Related Questions