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 .validation .Errors ;
9+ import org .springframework .web .bind .annotation .GetMapping ;
10+ import org .springframework .web .bind .annotation .ModelAttribute ;
11+ import org .springframework .web .bind .annotation .PostMapping ;
12+ import org .springframework .web .bind .annotation .RequestMapping ;
13+ import org .springframework .ui .Model ;
14+
15+ /**
16+ * Created by Chris Bay
17+ */
18+ @ Controller
19+ @ RequestMapping ("eventCategories" )
20+ public class EventCategoryController {
21+
22+ @ Autowired
23+ private EventCategoryRepository eventCategoryRepository ;
24+
25+ @ GetMapping
26+ public String displayAllCategories (Model model ) {
27+ model .addAttribute ("title" , "All Categories" );
28+ model .addAttribute ("categories" , eventCategoryRepository .findAll ());
29+ return "eventCategories/index" ;
30+ }
31+
32+ @ GetMapping ("create" )
33+ public String renderCreateEventCategoryForm (Model model ) {
34+ model .addAttribute ("title" , "Create Category" );
35+ model .addAttribute (new EventCategory ());
36+ return "eventCategories/create" ;
37+ }
38+
39+ @ PostMapping ("create" )
40+ public String processCreateEventCategoryForm (@ Valid @ ModelAttribute EventCategory eventCategory ,
41+ Errors errors , Model model ) {
42+
43+ if (errors .hasErrors ()) {
44+ model .addAttribute ("title" , "Create Category" );
45+ model .addAttribute (new EventCategory ());
46+ return "eventCategories/create" ;
47+ }
48+
49+ eventCategoryRepository .save (eventCategory );
50+ return "redirect:/eventCategories" ;
51+ }
52+
53+ }
0 commit comments