Example usage for org.springframework.validation BindingResult hasFieldErrors

List of usage examples for org.springframework.validation BindingResult hasFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult hasFieldErrors.

Prototype

boolean hasFieldErrors();

Source Link

Document

Are there any field errors?

Usage

From source file:com.jnj.b2b.storefront.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
@RequireHardLogIn//from   w w w .  j  a v a 2 s  . com
public String addNewBudget(@Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasFieldErrors()) {
        model.addAttribute(b2BBudgetForm);
        return getAddBudgetPage(model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        budgetFacade.addBudget(b2BBudgetData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("code", "text.company.budget.code.exists.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.created");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenGETBindError_returnBadRequest() throws Exception {
    when(singleJPAEntityService.findOne(TestEntity.class, 1l)).thenReturn(baseEntity);

    MvcResult result = mvc.perform(get("/entity/a")).andExpect(status().isBadRequest())
            .andExpect(view().name("errors/badrequest")).andReturn();

    BindingResult bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(),
            BindingResult.MODEL_KEY_PREFIX + "testEntityController", BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.MyCompanyPageController.java

protected String saveCostCenter(@Valid final B2BCostCenterForm b2BCostCenterForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasFieldErrors()) {
        model.addAttribute(b2BCostCenterForm);
        return addCostCenter(model);
    }/*  ww w. j  a  v a 2 s  . c  o m*/
    final B2BCostCenterData b2BCostCenterData = populateB2BCostCenterDataFromForm(b2BCostCenterForm);
    try {
        b2bCommerceCostCenterFacade.addCostCenter(b2BCostCenterData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the cost center details " + e);
        model.addAttribute(b2BCostCenterForm);
        bindingResult.rejectValue("code", "text.company.costCenter.code.exists.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return addCostCenter(model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageCostCenterBreadCrumbs();
    breadcrumbs.add(new Breadcrumb(ADD_COSTCENTER_URL, getMessageSource()
            .getMessage("text.company.costCenter.addPage", null, getI18nService().getCurrentLocale()), null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.company.costCenter.create.success");
    return String.format(REDIRECT_TO_COSTCENTER_DETAILS, urlEncode(b2BCostCenterData.getCode()));
}

From source file:com.jnj.b2b.storefront.controllers.pages.MyCompanyPageController.java

protected String saveCostCenter(@Valid final B2BCostCenterForm b2BCostCenterForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasFieldErrors()) {
        model.addAttribute(b2BCostCenterForm);
        return addCostCenter(model);
    }//from  w w  w .  j av  a2 s.co m
    final B2BCostCenterData b2BCostCenterData = populateB2BCostCenterDataFromForm(b2BCostCenterForm);
    try {
        b2bCostCenterFacade.addCostCenter(b2BCostCenterData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the cost center details " + e);
        model.addAttribute(b2BCostCenterForm);
        bindingResult.rejectValue("code", "text.company.costCenter.code.exists.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return addCostCenter(model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageCostCenterBreadCrumbs();
    breadcrumbs.add(new Breadcrumb(ADD_COSTCENTER_URL, getMessageSource()
            .getMessage("text.company.costCenter.addPage", null, getI18nService().getCurrentLocale()), null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.company.costCenter.create.success");
    return String.format(REDIRECT_TO_COSTCENTER_DETAILS, urlEncode(b2BCostCenterData.getCode()));
}

From source file:bd.gov.forms.web.FormBuilder.java

@RequestMapping(value = "/updateField", method = RequestMethod.POST)
public String updateField(@ModelAttribute("fieldCmd") Field field, BindingResult result,
        HttpServletRequest request, ModelMap model) {

    model.put("fieldCmd", field);
    model.put("formAction", "updateField");

    if (result.hasFieldErrors() || result.hasErrors()) {
        return "field";
    }/* w w w .j  av a2  s.c  o m*/

    log.debug("field->update");

    Form form = formDao.getForm(field.getFormIdStr());
    field.setFormId(form.getId());
    formDao.updateField(field);

    model.put("message", "msg.field.updated");
    model.put("msgType", "success");

    return "redirect:design.htm?formId=" + field.getFormIdStr();
}

From source file:bd.gov.forms.web.FormBuilder.java

@RequestMapping(value = "/saveField", method = RequestMethod.POST)
public String saveField(@ModelAttribute("fieldCmd") Field field, BindingResult result,
        HttpServletRequest request, ModelMap model) {

    model.put("fieldCmd", field);
    model.put("formAction", "saveField");

    if (result.hasFieldErrors() || result.hasErrors()) {
        return "field";
    }/*  w  w  w .  ja  v a 2 s.  co  m*/

    log.debug("field->save");

    Form frm = formDao.getForm(field.getFormIdStr());
    field.setFormId(frm.getId());
    field.setFieldId(Long.toString(System.nanoTime()) + new Long(new Random().nextLong()));

    formDao.updateOrder(field.getFormId(), field.getFieldOrder(), "+");
    formDao.saveField(field);

    model.put("message", "msg.field.submitted");
    model.put("msgType", "success");

    return "redirect:design.htm?formId=" + field.getFormIdStr();
}

From source file:bd.gov.forms.web.FormBuilder.java

@RequestMapping(value = "/saveForm", method = RequestMethod.POST)
public String saveForm(@ModelAttribute("formDetailsCmd") Form form, BindingResult result,
        HttpServletRequest request, ModelMap model) {

    model.put("formDetailsCmd", form);
    model.put("formAction", "saveForm");

    if (result.hasFieldErrors() || result.hasErrors()) {
        return "formDetails";
    }// w w  w.  j  a  v  a 2s  .  c o  m

    log.debug("form->save");

    form.setFormId(Long.toString(System.nanoTime()) + new Long(new Random().nextLong()));
    form.setStatus(1);

    formDao.saveForm(form);

    model.put("message", "msg.form.submitted");
    model.put("msgType", "success");

    return "redirect:formList.htm";
}

From source file:bd.gov.forms.web.FormBuilder.java

@RequestMapping(value = "/updateForm", method = RequestMethod.POST)
public String updateForm(@ModelAttribute("formDetailsCmd") Form form, BindingResult result,
        HttpServletRequest request, ModelMap model) {

    model.put("formDetailsCmd", form);
    model.put("formAction", "updateForm");

    if (result.hasFieldErrors() || result.hasErrors()) {
        return "formDetails";
    }//from w w  w  .  j  a  v a  2 s.c  o m

    log.debug("form->update");
    log.debug("file size: {}", form.getPdfTemplate().length);

    formDao.updateForm(form);

    model.put("message", "msg.form.updated");
    model.put("msgType", "success");

    return "redirect:formList.htm";
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPUTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;/*from  w w w .  j a  va2s  .  c o  m*/

    result = mvc.perform(put("/entity/1")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(put("/entity/1").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPOSTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;/*from w w  w .j  av  a  2s . c o m*/

    result = mvc.perform(post("/entity").param("id", "1")//@Id should be null on POSTs
            .param(firstName, firstName).param(lastName, lastName).param(testDateKey, testDate))
            .andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    assertThat(bindingResult.getFieldError("id"), notNullValue());

    result = mvc.perform(post("/entity")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(post("/entity").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}