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

3

4 5
import java.util.List;

6 7
import javax.validation.Valid;

8 9 10
import com.roshka.modelo.Cargo;
import com.roshka.repositorio.CargoRepository;
import org.springframework.beans.factory.annotation.Autowired;
11 12 13 14
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
15 16 17 18
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
19
import org.springframework.web.bind.annotation.PathVariable;
20 21
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
22
import org.springframework.web.bind.annotation.RequestMethod;
23 24 25 26 27 28 29 30
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CargoController {

    CargoRepository cargoRepo;

    @Autowired
31
    public CargoController(CargoRepository cargoRepo) {
32 33 34
        this.cargoRepo = cargoRepo;
    }

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

47 48 49 50 51
    @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));
52 53 54
        return "cargo-form";
    }

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

}