Monday, July 30, 2012

How to get a UI component in Backing bean without binding to a backing bean

Hello,

I thought of sharing useful tip, how to get a UI component ( SelectOneChoice, InputText, etc..) instance in a backing bean without exactly binding a UI component to a backing bean. This is very useful especially building complex UI screens and avoid binding too many UI components to a backing bean

Follow the below code in your backing bean


    UIComponent comp = null;
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    if (facesCtx != null)
    {
      UIComponent root = facesContext.getViewRoot();
      comp = findUIComponent(root, pComponentId);
}


    public UIComponent findUIComponent(UIComponent pBase, String pID) {
        if (pID.equals(pBase.getId()))
            return pBase;


        UIComponent child = null;
        UIComponent result = null;
        Iterator childrens = pBase.getFacetsAndChildren();
        while (childrens.hasNext() && (result == null)) {
            child = (UIComponent)childrens.next();
            if (pID.equals(child.getId())) {
                result = child;
                break;
            }
            result = findUIComponent(child, pID);
            if (result != null) {
                break;
            }
        }
        return result;
    }

No comments:

Post a Comment