@RequestMapping(value = "/components.html", method = RequestMethod.POST) public ModelAndView componentsManageSave( @ModelAttribute("productComponents") ProductComponents productComponents, ModelAndView mv) { Map<String, Integer> map = new HashMap<String, Integer>(); List<Component> components = productComponents.getComponents(); List<Component> nonZeroComponents = new ArrayList<Component>(); for (Component component : components) { if (component.getAmount() > 0) { // nonZeroComponents.add(component); } } productComponents.setComponents(nonZeroComponents); productsService.updateProductComponents(productComponents); mv.setViewName("redirect:all.html"); return mv; }
/** * Show components selection page TODO: form validation * * @param name * @param mv * @return */ @RequestMapping(value = "/components.html", method = RequestMethod.GET) public ModelAndView componentsManageView(@RequestParam("name") String name, ModelAndView mv) { Product managedProduct = new Product(); managedProduct.setName(name); Collection<Component> managedProductComponents = productsService.getProductComponents(managedProduct); Map<String, Integer> componentsAmountMap = new HashMap<String, Integer>(); for (Component component : managedProductComponents) { componentsAmountMap.put(component.getComponent().getName(), component.getAmount()); } // According to code allProducts instance is used only here Collection<Product> allProducts = productsService.getAllProducts(); ProductComponents productComponents = new ProductComponents(); productComponents.setProductName(name); // Iterate through available products end initialise amount for those which are already // components of chosen product List<Component> componentsList = productComponents.getComponents(); for (Product product : allProducts) { Component component = new Component(); component.setComponent(product); Integer amount = componentsAmountMap.get(product.getName()); if (amount != null) { component.setAmount(amount); } else { component.setAmount(0); } componentsList.add(component); } // Product name mv.addObject("name", name); mv.addObject("componentsCommand", productComponents); mv.setViewName("componentsManage"); return mv; }