2015-05-05 102 views
1

我想要一个在PrimeFaces 3.4中通过id找到UIComponent的方法。 我已经找到了一个方法来做到这一点,但它有一个方法visitTree(在PrimeFaces 5.2中可用),PrimeFaces 3.4不可用。通过PrimeFaces 3.4中的id找到组件id JSF 2.0

请有人可以帮我找到面板对象在下面的XHTML。

<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:p="http://primefaces.org/ui"> 

<h:head></h:head> 
<h:body> 
    <h:form id="form"> 
     <p:panel id="pnl"><h:outputText value="Yahoooo...."></h:outputText></p:panel> 
     <p:commandButton ajax="false" value="Toggle" actionListener="#{myBean.mytoggle}"/> 
    </h:form> 
</h:body> 
</html> 

Primefaces 5.2工作方法

public UIComponent findComponent(final String id) { 

    FacesContext context = FacesContext.getCurrentInstance(); 
    UIViewRoot root = context.getViewRoot(); 
    final UIComponent[] found = new UIComponent[1]; 

    root.visitTree(new FullVisitContext(context), new VisitCallback() {  
     @Override 
     public VisitResult visit(VisitContext context, UIComponent component) { 
      if(component.getId().equals(id)){ 
       found[0] = component; 
       return VisitResult.COMPLETE; 
      } 
      return VisitResult.ACCEPT;    
     } 
    }); 

    return found[0]; 

} 

回答

2

UIComponent#visitTree()的做法是不针对任何PrimeFaces版本。它特定于JSF 2.0。它在运行于JSF 2.x之上的任何PrimeFaces版本上应该同样好。如果你真的在运行JSF 1.x,它只会失败。

即使如此,标准的JSF API已经为作业提供了UIViewRoot#findComponent(),它只需要客户端ID,而不是组件ID。

UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot(); 
UIComponent component = view.findComponent("form:pnl"); 
// ... 

尽管如此,这是您的问题的错误解决方案。您似乎有兴趣对其执行setRendered(boolean)呼叫。你根本不应该这样做。你不应该对模型方面的观点感兴趣。反过来这样做。您应该改为设置视图应该反过来绑定的模型值。

这里有一个开球例如:

<h:form> 
    <p:panel rendered="#{not bean.hidden}"> 
     <h:outputText value="Yahoooo...." /> 
    </p:panel> 
    <p:commandButton value="Toggle" action="#{bean.toggle}" update="@form" /> 
</h:form> 

只需这豆:

private boolean hidden; 

public void toggle() { 
    hidden = !hidden; 
} 

public boolean isHidden() { 
    return hidden; 
}