marți, 27 ianuarie 2015

JSF Method to Recursively Find Component in Component Tree

Whenever you want to find a component in the component tree, you can use:
But, sometimes you need to get down to the most time consuming search. Use, this approach as the last solution (pass to it the component tree/sub-tree in which to search and the clientId of the component to find - if the searched component cannot be found, this method returns null):

import static org.omnifaces.util.Utils.isEmpty;
...
private static <C extends UIComponent> C findComponentRecursively(UIComponent component, String clientId) {

 if (isEmpty(clientId)) {
     return null;
 }

 for (UIComponent child : component.getChildren()) {
      UIComponent result;

      try {
          result = child.findComponent(clientId);
      } catch (IllegalArgumentException e) {
        continue;
      }

      if (result == null) {
          result = findComponentRecursively(child, clientId);
     }

     if (result != null) {
         return (C) result;
     }
 }
 return null;

}

Examples:
JSF page snippet
...
<h:body> 
 <h:graphicImage id="myImageId" url="http://1.bp.blogspot.com/-
  gtjrtr50mMY/VL0IcD0hbrI/AAAAAAAAA-I/8fmOugRBkvU/s1600/omniutil.png"/>
 <h:form id="myFormId">
  <h:panelGrid id="panelId">             
   Some text
   <h:outputText id="myOutputId" value="..." />
   <h:panelGroup id="myDivId" layout="block">
    <h:inputText id="myInputId" value="..."/>                                     
   </h:panelGroup>
   <h:commandButton id="myButtonId" value="Click me!" />           
  </h:panelGrid>
 </h:form>
</h:body>
...

·         search from UIViewRoot the component with clientId myImageId
UIComponent found = findComponentRecursively(UIViewRoot, "myImageId");

·         search from UIViewRoot the component with id, myInputId / clientId, myFormId:myInputId

UIComponent found = findComponentRecursively(UIViewRoot, "myInputId");

//this will perform faster
UIComponent found = findComponentRecursively(UIViewRoot, "myFormId:myInputId");


Note  Whenever you can, is better to use clientIds instead of ids, because the search perform faster.

Niciun comentariu:

Trimiteți un comentariu