Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find component by ID in JSF

I want to find some UIComponent from managed bean by the id that I have provided.

I have written the following code:

private UIComponent getUIComponent(String id) {         return FacesContext.getCurrentInstance().getViewRoot().findComponent(id) ;   } 

I have defined a p:inputTextarea as:

<p:inputTextarea id="activityDescription" value="#{adminController.activityDTO.activityDescription}" required="true" maxlength="120"     autoResize="true" counter="counter" counterTemplate="{0} characters remaining." cols="80" rows="2" /> 

Now if a call to the method as getUIComponent("activityDescription") it is returning null, but if I call it as getUIComponent("adminTabView:activityForm:activityDescription") then I can get the org.primefaces.component.inputtextarea.InputTextarea instance.

Is there any way to get the component with only the id i.e., "activityDescription" not the absolute id i.e., "adminTabView:activityForm:activityDescription"?

like image 886
Tapas Bose Avatar asked Jan 17 '13 11:01

Tapas Bose


1 Answers

You can use the following code:

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 != null                  && id.equals(component.getId())) {                 found[0] = component;                 return VisitResult.COMPLETE;             }             return VisitResult.ACCEPT;                       }     });      return found[0];  } 

This code will find only the first component in the tree with the id you pass. You will have to do something custom if there are 2 components with the same name in the tree (this is possible if they are under 2 different naming containers).

like image 117
Abbas Gadhia Avatar answered Sep 20 '22 21:09

Abbas Gadhia