JSF: How to find a component in the view root

On March 15, 2011, in JSF, by lucasterdev

Use the following functions. (All the credit goes to mert)

public static UIComponent findComponentInRoot(String id) {
    UIComponent component = null;

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext != null) {
      UIComponent root = facesContext.getViewRoot();
      component = findComponent(root, id);
    }

    return component;
}

public static UIComponent findComponent(UIComponent base, String id) {
    if (id.equals(base.getId()))
      return base;

    UIComponent kid = null;
    UIComponent result = null;
    Iterator kids = base.getFacetsAndChildren();
    while (kids.hasNext() && (result == null)) {
      kid = (UIComponent) kids.next();
      if (id.equals(kid.getId())) {
        result = kid;
        break;
      }
      result = findComponent(kid, id);
      if (result != null) {
        break;
      }
    }
    return result;
}
 

Leave a Reply