我可以在加载页面后动态地向页面添加命令按钮,但不能在页面加载之前添加。
在下面的代码中,单击标有添加按钮的命令按钮。视图操作失败,因为执行rootview.findcomponent时,panelGrid为null。
<f:metadata>
<f:viewAction action="#{modStepMBean.updateClientViewAction()}"/>
</f:metadata>
<h:head>
<title>Start Node Input</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h:form id="picNumForm" styleClass="form" prependId="false">
<p:panelGrid id="MediaBtnGrid" columns="7">
</p:panelGrid>
</h:form>
<h:form>
<p:commandButton value="Add Buttons" action="#{modStepMBean.updateClientViewAction()}">
</p:commandButton>
</h:form>
托管bean
@SessionScoped
@RolesAllowed({"Users"})
@Named
public class ModStepMBean implements Serializable {
private UIComponent buttonGrid;
private void btnCount(Integer mediaCount) {
FacesContext ctx = FacesContext.getCurrentInstance();
UIViewRoot rootView = ctx.getViewRoot();
buttonGrid = (PanelGrid) rootView.findComponent("picNumForm:MediaBtnGrid");
buttonGrid.getChildren().clear();
for (int i = 0; i < mediaCount; i++) {
addMediaBut(i + 1);
}
}
private void addMediaBut(Integer num) {
String strNum = Integer.toString(num);
CommandButton button = new CommandButton();
button.setValue("Media" + strNum);
button.setId("MediaBut" + strNum);
FacesContext facesCtx = FacesContext.getCurrentInstance();
ELContext elContext = facesCtx.getELContext();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
MethodExpression methodExpression = null;
methodExpression = elFactory.createMethodExpression(elContext, "#{modStepMBean.selPic(" + strNum + ")}", null, new Class[]{});
button.setActionExpression(methodExpression);
buttonGrid.getChildren().add(button);
}
public void updateClientViewAction()
{
btnCount(2);
RequestContext ctx = org.primefaces.context.RequestContext.getCurrentInstance();
ctx.update("picNumForm");
}
这种方法有误吗?如果是这样,那么正确的方法是什么?我错过了什么?感谢