CargoController.java 1.94 KB
Newer Older
1 2
package com.roshka.controller;

3

4 5 6 7 8 9 10
import com.roshka.modelo.Cargo;
import com.roshka.repositorio.CargoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
11
import org.springframework.web.bind.annotation.PathVariable;
12 13
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
14
import org.springframework.web.bind.annotation.RequestMethod;
15 16 17 18 19 20 21 22
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CargoController {

    CargoRepository cargoRepo;

    @Autowired
23
    public CargoController(CargoRepository cargoRepo) {
24 25 26
        this.cargoRepo = cargoRepo;
    }

27
    @RequestMapping("/cargos")
28
    public String menuCargos(Model model,
29
                            @RequestParam(required = false) String nombre
30
                            ) {
31 32 33
        if(nombre == null || nombre.trim().isEmpty()) model.addAttribute("cargos", cargoRepo.findAll());
        else model.addAttribute("cargos", cargoRepo.findByNombreContainingIgnoreCase(nombre));
        return "cargos";
34 35
    }

36 37 38 39 40
    @RequestMapping(path = {"/cargo","/cargo/{id}"}, method = RequestMethod.GET)
    public String formCargo(Model model,@PathVariable(required = false) Long id) {

        if(id == null) model.addAttribute("cargo", new Cargo());
        else model.addAttribute("cargo", cargoRepo.getById(id));
41 42 43
        return "cargo-form";
    }

44 45
    @PostMapping(path = {"/cargo","/cargo/{id}"})
    public String guardarCargo(@ModelAttribute Cargo cargo, BindingResult result, @PathVariable(required = false) Long id) {
46
        if(result.hasErrors()); 
47
        if(id != null ) cargo.setId(id);
48 49 50 51 52 53
        cargoRepo.save(cargo);
        System.out.println(cargo.getNombre());
        return "redirect:/cargos";
    }

}