在 JSF 中按 ID 查找组件 [英] Find component by ID in JSF

查看:23
本文介绍了在 JSF 中按 ID 查找组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过我提供的 id 从托管 bean 中找到一些 UIComponent.

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

我编写了以下代码:

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

我已经定义了一个 p:inputTextarea 为:

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" />

现在,如果以 getUIComponent("activityDescription") 调用该方法,它将返回 null,但如果我将其调用为 getUIComponent("adminTabView:activityForm:activityDescription") 然后我可以得到 org.primefaces.component.inputtextarea.InputTextarea 实例.

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.

有什么方法可以获取只有 id 的组件,即activityDescription"而不是绝对 id,即adminTabView:activityForm:activityDescription"?

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

推荐答案

可以使用以下代码:

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];

}

此代码将仅查找树中具有您传递的 id 的第一个组件.如果树中有 2 个具有相同名称的组件(如果它们位于 2 个不同的命名容器下,这是可能的),您将不得不进行一些自定义操作.

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).

这篇关于在 JSF 中按 ID 查找组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆