在JSF中按ID查找组件 [英] Find component by ID in JSF
问题描述
我想通过提供的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
定义为:
<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
&& component.getId() != null
&& component.getId().equals(id)) {
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屋!