Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF commandButton not working when created dynamically with java

Tags:

jsf

primefaces

Using primeFaces I have the following button:

<p:commandButton value="Submit" action="#{createDeal.saveDeal}" update="myPanel" />

This works just fine. However I want to generate that button using java. I have the following code:

CommandButton submit = new CommandButton();
submit.setValue("Submit");
submit.setUpdate("myPanel");
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
MethodExpression methodExpression =null;
methodExpression = elFactory.createMethodExpression(elContext,"#{createDeal.saveDeal}",String.class, new Class[]{});
submit.addActionListener(new MethodExpressionActionListener(methodExpression));
submit.setActionExpression(methodExpression);
createButtons.getChildren().add(submit);

When I click submit, my form validates (which is done using the setRequired function on the input), but the form never hits my createDeal class. What am I doing wrong that the inline button works, but the java generated one does not.

One note. The button created inline using primefaces, is there on page load. The button attempted to be added with java is not done until after an Ajax call is made to generate both the form AND button.

Any assistance would be helpful.

Thanks.

like image 901
FatimahM Avatar asked Nov 01 '22 13:11

FatimahM


1 Answers

Thanks to BalusC for all your help. I am still not sure how I missed this! The following works:

CommandButton submit = new CommandButton();
submit.setValue("Submit");
submit.setUpdate("myPanel");
submit.setId("create"+panelClass);
FacesContext facesCtx = FacesContext.getCurrentInstance();
ELContext elContext = facesCtx.getELContext();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
MethodExpression methodExpression =null;
methodExpression = elFactory.createMethodExpression(elContext,"#    {createDeal.saveDeal}",null, new Class[]{});
submit.setActionExpression(methodExpression);
createButtons.getChildren().add(submit);

The null pointer exception was unrelated. It looks like simply adding the ID and removing the ActionListener did the trick. Much obliged!

like image 155
FatimahM Avatar answered Nov 15 '22 12:11

FatimahM