Example usage for org.springframework.validation FieldError getField

List of usage examples for org.springframework.validation FieldError getField

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getField.

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

From source file:cz.muni.fi.dndtroopsweb.controllers.TroopController.java

/**
 * Creates troop based on form provided//  w  ww  .  j a  v a 2s .  co  m
 *
 * @param formBean troop to be created
 * @return details of newly created troop
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("troopCreate") TroopCreateDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("create(formBean={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "troop/new";
    }

    Long id = troopFacade.createTroop(formBean);

    redirectAttributes.addFlashAttribute("alert_success", "Troop " + id + " was created");
    return "redirect:" + uriBuilder.path("/troop/list").toUriString();
}

From source file:cz.muni.fi.dndtroopsweb.controllers.TroopController.java

/**
 * Changes money based on form for chosen troop
 *
 * @param formBean troop to be modified/*from ww w  .  j  ava 2  s .c o m*/
 * @return details of modified troop
 */
@RequestMapping(value = "/cash/{id}", method = RequestMethod.POST)
public String cash(@PathVariable long id, @Valid @ModelAttribute("troop") TroopDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("update money(troop={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "troop/money";
    }
    troopFacade.changeMoney(id, formBean.getMoney());
    //Long id = formBean.getId();
    redirectAttributes.addFlashAttribute("alert_success", "Money updated");
    return "redirect:" + uriBuilder.path("/troop/details/{id}").buildAndExpand(id).encode().toUriString();
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/calculate", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String calculateDuration(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDurationDTO appointmentDurationDTO,
        BindingResult bindingResult, UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    model.addAttribute("proceduresOptions", Procedure.values());

    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }//from  w  w  w. j a  va2  s.c om
        return "appointments/calculate";
    }

    AppointmentDTO appointmentDTO = createFromDurationDTO(appointmentDurationDTO);

    Long duration = facade.calculateAppointmentDuration(appointmentDTO) * 60 * 1000; // in miliseconds
    Date endTime = new Date(appointmentDTO.getStartTime().getTime() + duration);
    appointmentDTO.setEndTime(endTime);

    model.addAttribute("appointment", appointmentDTO);

    return "appointments/create";
}

From source file:th.co.geniustree.dental.controller.ValidationExceptionHandler.java

private Map<String, ValidationErrorMessage> extractError(MethodArgumentNotValidException ex) {
    Map<String, ValidationErrorMessage> returnError = new HashMap<>();
    List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();

    for (ObjectError error : allErrors) {
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError) error;
            ValidationErrorMessage msg = new ValidationErrorMessage();
            msg.setMessage(fieldError.getDefaultMessage());
            msg.setType(fieldError.getObjectName());
            returnError.put(fieldError.getField(), msg);
        }/*www  .j  a v  a  2  s  .  c  om*/
    }
    return returnError;
}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result, @PathVariable int id, HttpSession session) {
    //System.out.println("Update");
    if (!result.hasErrors()) {
        //System.out.println("done");
        session.setAttribute("user", user);
        userService.updateUserInfo(id, user);
        return "redirect:/users";
    } else {//  w  w  w .  j  av  a  2 s.  c o  m
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
        return "userDetail";
    }
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String update(Model model, @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO,
        BindingResult bindingResult, UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }//from   w w  w .  ja  v  a 2s . c  o  m

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/edit";
    }
    Long id = appointmentDTO.getId();
    try {
        facade.updateAppointment(appointmentDTO);

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was edited.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile editing: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment #" + id + " was not edited.");
        return "redirect:/";
    }
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createAppointment(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());

        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }/*from   w w w. ja v  a 2  s.c  o m*/

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/create";
    }
    try {
        appointmentDTO = facade.createAppointment(appointmentDTO);
        Long id = appointmentDTO.getId();

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was created.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile creating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment was not created.");
        return "redirect:/";
    }
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse addUser(@Valid @RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);/*from  www  . j  av  a  2 s. co m*/

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.addUser(userData);
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse modifyUser(@RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);//from  w ww.  j a v  a 2s .  c  o  m

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.modifyUser(userData);
}

From source file:com.oak_yoga_studio.controller.FacultyController.java

@RequestMapping(value = "/updateFacultyProfile", method = RequestMethod.POST)
public String updateUser(@Valid Faculty facultyUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Faculty) session.getAttribute("loggedUser")).getId();
        Faculty faculty = facultyService.getFacultyById(Id);

        faculty.setFirstName(facultyUpdate.getFirstName());
        faculty.setLastName(facultyUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        faculty.setEmail(facultyUpdate.getEmail());

        try {//from w  w w.ja  v a2s . c o m
            System.out.println("Imageeeeeeeeeee - " + file.getBytes());
            if (file.getBytes().length != 0) {
                faculty.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        facultyService.updateFaculty(Id, faculty);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/facultyProfile";
}