Find component by ID in JSF

前端 未结 5 1247
梦如初夏
梦如初夏 2020-11-29 01:48

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

I have written the following code:

private UIComponen         


        
5条回答
  •  情深已故
    2020-11-29 01:59

    Maybe it's not possible. The FacesContext.getCurrentInstance().getViewRoot().findComponent(id) method returns only one UIComponent. The ViewRoot is constructed as a tree so if you have two forms in the view, each one with a component with id="text", they will have it's parent components added to the id so they won't conflict. If you put the two id="text" components within the same form, you will have java.lang.IllegalStateException thrown.

    If you want to find all components with the searched id, you could write a method that implements:

    List foundComponents = new ArrayList();
    for(UIComponent component: FacesContext.getCurrentInstance().getViewRoot().getChildren()) {
        if(component.getId().contains("activityDescription")){
            foundComponents.add(component);
        }
    }
    

    Or if you want to find the first occurrence:

    UIComponent foundComponent;
    for(UIComponent component: FacesContext.getCurrentInstance().getViewRoot().getChildren()) {
        if(component.getId().contains("activityDescription")){
            foundComponent = component;
            break;
        }
    }
    

提交回复
热议问题