如何通过 icefaces 中的组件 ID 获取 UIComponent

How to get a UIComponent by its component id in icefaces

我正在尝试访问一个 icefaces 组件,确切地说是一个 Accordion,因此我可以从我的 bean 中设置它的 activeIndex。问题是返回值始终为空。这是我的代码。

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;
    }

我这样称呼这个方法:

Accordion acco = (Accordion)findComponentInRoot("menuFormId:menu");

我的页面看起来像这样或者说其中的一部分:

<h:form id="menuFormId">
        <icecore:singleSubmit />

        <ace:accordion id="menu" collapsible="true" autoHeight="false" >

            <ace:accordionPane id="system" title="#{msgs.LABEL_ADMINISTRATION}"
                rendered="#{navigationCtrl.functionList['GESUTAD'] or navigationCtrl.functionList['GESPROF'] or navigationCtrl.functionList['GESUTTOM'] or navigationCtrl.functionList['SYNCPRC']}">

                <div class="divLinkStyle">
                    <ice:commandLink rendered="#{navigationCtrl.functionList['GESPROF']}" styleClass="linkMenu" action="#{navigationCtrl.redirectConsulterProfil}"
                        onmouseover="this.style.backgroundColor='#DEEDF8'" onmouseout="this.style.backgroundColor='#FFFFFF'">
                        <h:graphicImage value="../resources/images/util.png" />
                        <h:outputLabel value="#{msgs.LABEL_GESTION_PROFIL}" style="cursor: pointer;" />
                    </ice:commandLink>
                </div>
...

有什么想法吗?

我的 bean 是会话范围的。

我正在使用 icefaces 3.3.0 和 jsf 2.2

您混淆了组件 ID 和客户端 ID。您将客户端 ID "menuFormId:menu" 而不是组件 ID "menu" 传递给您的实用程序方法,而实用程序方法实际上是通过组件 ID 而不是客户端 ID 找到组件。

只需使用UIViewRoot#findComponent()

public static UIComponent findComponentInRoot(String id) {
    return FacesContext.getCurrentInstance().getViewRoot().findComponent(id);
}

与具体问题无关。你在这里犯了一个设计错误。模型不应该对视图感兴趣。应该反过来。将 activeIndex 设置为 bean 属性 并让视图以通常的方式挂钩它。

<ace:accordion ... activeIndex="#{bean.activeIndex}">

在任何情况下,您正在尝试 grab/create/bind/manipulate/whatever 支持 bean 中的物理 UIComponent 实例 class,您绝对应该停止编码并三思而后行,如果您真的在做事情的正确方法。如果您无法找到正确的方法,请在 Stack Overflow 上询问是否有必要。