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

3

4 5
import javax.validation.Valid;

6 7 8 9 10 11 12
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;
13
import org.springframework.web.bind.annotation.PathVariable;
14 15
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
16
import org.springframework.web.bind.annotation.RequestMethod;
17 18 19 20 21 22 23 24
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CargoController {

    CargoRepository cargoRepo;

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

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

38 39 40 41 42
    @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));
43 44 45
        return "cargo-form";
    }

46
    @PostMapping(path = {"/cargo","/cargo/{id}"})
47 48 49 50 51
    public String guardarCargo(@Valid @ModelAttribute Cargo cargo, BindingResult result, @PathVariable(required = false) Long id, Model model) {
        if(result.hasErrors() || (id==null && cargoRepo.existsByNombreIgnoreCase(cargo.getNombre())  )){
            model.addAttribute("mismoNombre", true);
            return "cargo-form";
        }; 
52
        if(id != null ) cargo.setId(id);
53 54 55 56 57 58
        cargoRepo.save(cargo);
        System.out.println(cargo.getNombre());
        return "redirect:/cargos";
    }

}