|
| 1 | +package org.launchcode.codingevents.controllers; |
| 2 | + |
| 3 | +import jakarta.validation.Valid; |
| 4 | +import org.launchcode.codingevents.data.EventCategoryRepository; |
| 5 | +import org.launchcode.codingevents.models.EventCategory; |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; |
| 7 | +import org.springframework.stereotype.Controller; |
| 8 | +import org.springframework.ui.Model; |
| 9 | +import org.springframework.validation.Errors; |
| 10 | +import org.springframework.web.bind.annotation.GetMapping; |
| 11 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 12 | +import org.springframework.web.bind.annotation.PostMapping; |
| 13 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 14 | + |
| 15 | +@Controller |
| 16 | +@RequestMapping("eventCategories") |
| 17 | +public class EventCategoryController { |
| 18 | + |
| 19 | + @Autowired |
| 20 | + private EventCategoryRepository eventCategoryRepository; |
| 21 | + |
| 22 | + @GetMapping |
| 23 | + public String displayAllCategories(Model model) { |
| 24 | + model.addAttribute("title", "All Categories"); |
| 25 | + model.addAttribute("categories", eventCategoryRepository.findAll()); |
| 26 | + |
| 27 | + return "eventCategories/index"; |
| 28 | + } |
| 29 | + |
| 30 | + @GetMapping("create") |
| 31 | + public String renderCreateEventCategoryForm(Model model) { |
| 32 | + model.addAttribute("title", "Create Category"); |
| 33 | + model.addAttribute(new EventCategory()); |
| 34 | + |
| 35 | + return "eventCategories/create"; |
| 36 | + } |
| 37 | + |
| 38 | + @PostMapping("create") |
| 39 | + public String processCreateEventCategoryForm(@Valid @ModelAttribute EventCategory eventCategory, |
| 40 | + Errors errors, Model model) { |
| 41 | + if(errors.hasErrors()) { |
| 42 | + model.addAttribute("title", "Create Category"); |
| 43 | + model.addAttribute(new EventCategory()); |
| 44 | + |
| 45 | + return "eventCategories/create"; |
| 46 | + } |
| 47 | + |
| 48 | + eventCategoryRepository.save(eventCategory); |
| 49 | + return "redirect:/eventCategories"; |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | +} |
0 commit comments