ApollonDigital
ApollonDigital

Reputation: 973

Spring form:errors customization

I'm trying to implement my own form:errors tag, or wrap it on a custom tag. The reason I want to do that is to customize the message, display some icons etc. I am not sure if <form:errors /> is good enough for that purposes.

I found that piece of code which can replace <form:errors path="foo" />

<spring:bind path="foo">
  <c:if test="${status.error}">
    <img src="<c:url value="/resources/images/warning.png"/>" 
       width="31" height="32" class="error_tooltip" title="${status.errorMessage}" />
  </c:if>
</spring:bind>

BTW ... I don't know how this works if someone can explain. I tried to put that code inside a custom tag (tag file) but:
javax.servlet.jsp.JspTagException: Neither BindingResult nor plain target object for bean name 'form' available as request attribute
Any suggestions?

ps. I also want to find a solution to return feedback with ajax requests. I am not sure if JSONize the BindingResult object is a good solution, so I will propably create my own 'Feedback' object.
If <form:error/> tag can't help me with customizations, it would be nice to use 'Feedback' object for both normal and ajax requests (using model to pass into JSPs, or JSON responses for ajax).

EDIT: Here is my tag code:

<%@attribute name="name" required="true" %>

<spring:bind path="${name}">
  <c:if test="${status.error}">
    <img src="<c:url value="/resources/images/warning.png"/>" 
       width="31" height="32" class="error_tooltip" title="${status.errorMessage}" />
  </c:if>
</spring:bind>

Upvotes: 0

Views: 1240

Answers (1)

Benoit Wickramarachi
Benoit Wickramarachi

Reputation: 6216

Yes use the tag <form:errors> to customized form validation. In order for this tag to work you need to have a BindingResult in your controller:

@RequestMapping(value="/save",method=RequestMethodPOST)
public String save(@Valid Bean yourBean, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "/create"; // your form
    } else {
        yourBean= beanService.save(yourBean);
        return "redirect:/view/" + yourBean.getId(); // other action  
    } 
}

You can read a good tutorial on form validation customization.

Upvotes: 1

Related Questions