Reputation: 33
I want a method which finds a UIComponent
by id in PrimeFaces 3.4.
I already found a method to do this but it has a method visitTree(available in PrimeFaces 5.2) which is not available for PrimeFaces 3.4.
Please can someone help me find panel object in below 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 working method
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];
}
Upvotes: 1
Views: 7210
Reputation: 1108722
The UIComponent#visitTree()
approach is not specific to any PrimeFaces version. It's specific to JSF 2.0. It should work equally good on any PrimeFaces version running on top of JSF 2.x. It would only fail if you're actually running JSF 1.x.
Even then, the standard JSF API already offers UIViewRoot#findComponent()
for the job, it only takes a client ID, not a component ID.
UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot();
UIComponent component = view.findComponent("form:pnl");
// ...
Nonetheless, this is the wrong solution to your problem. You appear to be interested in performing setRendered(boolean)
call on it. You should not be doing that at all. You should not be interested in the view from the model side on. Do it the other way round. You should instead set a model value which the view should in turn be bound to.
Here's a kickoff example:
<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>
With just this in bean:
private boolean hidden;
public void toggle() {
hidden = !hidden;
}
public boolean isHidden() {
return hidden;
}
Upvotes: 5