I can dynamically add command buttons to the page after the page is loaded, but not before the page is loaded.
In the code below, clicking the command button labeled add buttons works. The view action fails because panelGrid is null when rootview.findcomponent is executed.
<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>
The managed 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");
}
Is this approach wrong? If so, what is the correct approach? Did I miss something? Thanks