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

3

4 5 6
import com.roshka.modelo.Cargo;
import com.roshka.repositorio.CargoRepository;
import org.springframework.beans.factory.annotation.Autowired;
7 8 9 10
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
11 12 13
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
14 15 16
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
17 18

@Controller
19
@RequestMapping("/cargos")
20 21 22 23 24
public class CargoController {

    CargoRepository cargoRepo;

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

29
    @RequestMapping()
30
    public String menuCargos(Model model,@RequestParam(required = false) String nombre,@RequestParam(defaultValue = "0")Integer nroPagina) {
31
        final Integer CANTIDAD_POR_PAGINA = 10;
32
        Pageable page = PageRequest.of(nroPagina,CANTIDAD_POR_PAGINA,Sort.by("id"));
33 34 35 36 37 38
        if(nombre == null || nombre.trim().isEmpty()) {
            Page<Cargo> CargoPag=cargoRepo.findAll(page);
            model.addAttribute("cargos", CargoPag.getContent());
            model.addAttribute("pages", CargoPag.getTotalPages());
        }
        else {
39
            Page<Cargo> CargoPag=cargoRepo.findByNombreContainingIgnoreCase(nombre.trim(),page);    
40 41 42
            model.addAttribute("pages", CargoPag.getTotalPages());
            model.addAttribute("cargos", CargoPag.getContent());
        }
43
        return "cargos";
44 45
    }

46
    @RequestMapping(path = {"/agregar","/modificar/{id}"}, method = RequestMethod.GET)
47 48 49 50
    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));
51 52 53
        return "cargo-form";
    }

54
    @PostMapping(path = {"/agregar","/modificar/{id}"})
55 56 57 58 59
    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";
        }; 
60 61 62 63
        if(id != null ){
            cargo.setId(id);
            cargo.setExisteConvocatoria(cargoRepo.getById(id).isExisteConvocatoria());
        } 
64 65 66 67 68
        cargoRepo.save(cargo);
        return "redirect:/cargos";
    }

}