Tuesday, December 30, 2008

Show Business Logic Validation/Error/Exception in JSF pages Using AJAX4JSF in Seam Application.

I am facing issue while adding FacesMessages to the Current FacesConfig. My Implementation is as Follows
public void addUser(){
String message = "Duplicate user name. Username already exists";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage( FacesMessage.SEVERITY_INFO, message, message));

But I am getting the following warning and I am not able to Show the error message in the Client Side Page.

WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.sourceId=rstReport:timeHorizonDecoration:timeHorizon[severity=(ERROR 2), summary=(value is required), detail=(value is required)]

The Solution I made as
I have Created a Utility class to add the Error messages into the Current FacesConfig Instance.

import java.util.Iterator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

public class ErrorMsgUtil {
   public static void addError(FacesMessage.Severity severity,String componentId,String    messageText){
       FacesMessage message = new FacesMessage(messageText);
       FacesContext context = FacesContext.getCurrentInstance();
       UIComponent component = findComponent(context.getViewRoot(), componentId);
       context.addMessage(component.getClientId(context), message);

   private static UIComponent findComponent(UIComponent parent, String id) {
       if(id.equals(parent.getId())) {
          return parent;
       Iterator kids = parent.getFacetsAndChildren();
       while(kids.hasNext()) {
          UIComponent kid = kids.next();
          UIComponent found = findComponent(kid, id);
          if(found != null) {
             return found;
       return null;

And I have Called the Error Method as Follows

public void addUser(){
      ... addUser ... Code
   }catch(UserAlreadyExistException e){
      String message = "Duplicate user name. Username already exists";
      ErrorMsgUtil.addError(FacesMessage.SEVERITY_ERROR,"errorMsg", msg);

and added one h:message for="errorMsg";

It is working fine for the AJAX4JSF Page implementation.

No comments: