JSF ViewState not updated when submitting 2 forms - jsf-2

I have a though issue with JSF 2. I use Mojarra 2.1.14 with Primefaces 3.1.4
I have a page with 2 forms : formA and formB. The two forms contains each the ViewState in an hidden input field.
<h:form id="formA" binding="#{sessionBean.formA}">
<h:commandButton value="formA" action="#{sessionBean.actionA}">
<f:ajax/>
</h:commandButton>
</h:form>
<h:form id="formB" binding="#{sessionBean.formB}">
<h:commandButton value="formB" action="#{sessionBean.actionB}">
<f:ajax/>
</h:commandButton>
</h:form>
User submits formA with an Ajax action. Inside the Java action I update explicitly formA and formB (which are binded).
public void actionA(){
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(formA.getClientId());
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(formB.getClientId());
System.out.println("action A!!");
}
public void actionB(){
System.out.println("action B!!");
}
In the Ajax responses there is the HTML code for formA and formB ( element) and the ViewState.
JSF updates the HTML of formA and formB and set the ViewState of the calling form : formA. formB do not contains any ViewState.
User submit formB with an Ajax action. Because ViewState is not defined, postBack is false and the renderResponse is set to true in the RESTORE phase, skipping the INVOKE APPLICATION phase: the action is not called. After the response VIEW_STATE is updated and if user sumbit formB, the action is called.
Is it a JSF 2 bug or limitation? Or Do I do something wrong ?
You can find a maven projet on GitHub:
https://github.com/nithril/jsf-multiple-form
Thanks in advance for your help!

Problem you are facing is connected with known issue with JSF JavaScript library. Workaround is to explicitly set client id of another form in rendered attribute of f:ajax tag:
<h:form id="formA" binding="#{sessionBean.formA}">
<h:commandButton value="formA" action="#{sessionBean.actionA}">
<f:ajax render=":formB #form"/>
</h:commandButton>
</h:form>
<h:form id="formB" binding="#{sessionBean.formB}">
<h:commandButton value="formB" action="#{sessionBean.actionB}">
<f:ajax render=":formA #form"/>
</h:commandButton>
</h:form>
More about this:
Ajax rendering of content which contains another form
javax.faces.ViewState is missing after ajax render
Rendering other form by ajax causes its view state to be lost, how do I add this back?

There is an alternative trick if you use MyFaces 2.0.x / 2.1.x that will update the forms correctly, adding the following script:
window.myfaces = window.myfaces || {};
myfaces.config = myfaces.config || {};
//set the config part
myfaces.config.no_portlet_env = true;
See JSF Ajax and Multiple Forms.
This option is a lot better because you don't need to worry about fix every place in your webapp where you use multiple forms, just add it to the main template and that's it.

Related

Render or update a page while still running inside a method

I was wondering if you could render or update a page while you still inside a method;
here is an example:
the .xhtml file:
<h:form id="form">
<h:commandButton value="change" actionListener="#{bean.changeText}">
<f:ajax render="out" />
</h:commandButton>
<h:outputLabel id="out" value="#{bean.text}" />
</h:form>
and here is the changeText Method:
public void changeText() throws InterruptedException{
text = "test1";
FacesContext.getCurrentInstance().renderResponse();
Thread.sleep(2000);
text = "test2";
}
Now is it possible to set the output label (id = out) to be rendered (or changed) to "test1", then after the 2 second have elapsed it changes to "test2"?
Well looking at the JSF life cycle i thought it isnt possible, but maybe i got the life cycle wrong, or one of you guys know a work around.
No, that's not possible. The render response only starts once the action method returns.
There are basically 2 ways to achieve the desired behavior: polling or pushing. Based on your question history, you're using Java EE 7 + JSF 2.2 + PrimeFaces. You could for pushing use PrimeFaces <p:socket> or homegrow one using Java EE 7's new WebSocket API (JSR-356).

Displaying a message from managed bean with primefaces confirmation dialog component

in my page , i'm trying to display a confirmation dialog after clicking a button .In the confirmation dialog i used the attribute message to display it , this message is taken value after clicking the button . So i did it like that :
<p:commandButton value="Delete" update="testPlanetree" id="deleteBtn"
disabled="#{projectTestManagementMB.disable}" oncomplete="deleteConfirmation.show()"
action="#{projectTestManagementMB.testFn}"/>
<p:confirmDialog id="confirmDialog" message="#
{projectTestManagementMB.deleteConfirmationMsg}"
header="Confirming Deleting Process" severity="alert"
widgetVar="deleteConfirmation">
<p:commandButton id="confirm" value="Yes Sure" update="messages"
oncomplete="deleteConfirmation.hide()" />
<p:commandButton id="decline" value="Not Yet"
onclick="deleteConfirmation.hide()" type="button" />
</p:confirmDialog>
ProjectTestManagementMB Managed Bean :
private String deleteConfirmationMsg;//with getters and setters
public void testFn(){
deleteConfirmationMsg="do you want to delete ...";
}
The problem is that the deleteConfirmationMsg never take the value "do you want to delete ..." (is always empty)
Any idea will be appreciated
The <p:confirmDialog> has already generated its HTML representation on the very first HTTP request returning the page with the form and the dialog. It's merely hidden by CSS and is supposed to be shown/hidden by JS. When you change the confirm message afterwards in a bean action method, then it won't be reflected in the generated HTML output as long as you don't ajax-update it.
So, in order to get the changed message being reflected, you'd need to update the HTML representation of the <p:confirmDialog> in the client side before showing it in the oncomplete. You can for this use the update attribute of the command button which should show the dialog.
<p:commandButton ... update="confirmDialog testPlanetree">
try this i should works :
<p:commandButton value="Delete" update="testPlanetree" id="deleteBtn" actionListener="#
{projectTestManagementMB.testFn}"
disabled="# {projectTestManagementMB.disable}"
oncomplete="deleteConfirmation.show()" />

How to find indication of a Validation error (required="true") while doing ajax command

I have a form inside a dialog which I close by clicking on commandbutton with ajax ,
like this
<h:commandButton value="Add" action="#{myBean.addSomething(false)}"
id="add_something_id" >
<f:ajax render="#form someTable" execute="#form"
onevent="closeAddNewSomethingDialogIfSucceeded"></f:ajax>
</h:commandButton>
and here is the js code for closing the dialog
function closeAddNewSomethingDialogIfSucceeded(data) {
if(data.status === 'success') {
$("#dialog_id").dialog("close");
}
}
No problems till here...
Now I changed some of the dialog form fields into required="true" and now I want to prevent the closing of the dialog of i got validation errors...
But the ajax data.status still reaches its success state , and I can't figure out what indication of validation failure I can hook on...
any ideas?
Thanks to BalusC answer I did the following:
in JSF , added :
<h:panelGroup id="global_flag_validation_failed_render">
<h:outputText id="global_flag_validation_failed" value="true"
rendered="#{facesContext.validationFailed}"/>
</h:panelGroup>
the f:ajax was changed into
<f:ajax render="#form someTable global_flag_validation_failed_render"
and in js added the following check
if(data.status === 'success') {
if($("#global_flag_validation_failed").length === 0){
$("#dialog_id").dialog("close");
}
}
Not specifically for required="true", but you can check by #{facesContext.validationFailed} if validation has failed in general. If you combine this with checking if the button in question is pressed by #{not empty param[buttonClientId]}, then you can put it together in the rendered attribute of the <h:outputScript> as follows:
<h:commandButton id="add_something_id" binding="#{add}" value="Add" action="#{myBean.addSomething(false)}">
<f:ajax execute="#form" render="#form someTable" />
</h:commandButton>
<h:outputScript rendered="#{not empty param[add.clientId] and not facesContext.validationFailed}">
$("#dialog_id").dialog("close");
</h:outputScript>
(note that you need to make sure that the script is also re-rendered by f:ajax)
A bit hacky, but it's not possible to handle it in the onevent function as the standard JSF implementation doesn't provide any information about the validation status in the ajax response.
If you happen to use RichFaces, then you could just use EL in the oncomplete attribute of the <a4j:xxx> command button/link. They are namely evaluated on a per-request basis instead of on a per-view basis as in standard JSF and PrimeFaces:
<a4j:commandButton ... oncomplete="if (#{!facesContext.validationFailed}) $('#dialog_id').dialog('close')" />
Or if you happen to use PrimeFaces, then you could take advantage of the fact that PrimeFaces extends the ajax response with an additional args.validationFailed attribute which is injected straight in the JavaScript scope of the oncomplete attribute:
<p:commandButton ... oncomplete="if (args && !args.validationFailed) $('#dialog_id').dialog('close')" />
(note that & is been used instead of &, because & is a special character in XML/XHTML)
Or you could use the PrimeFaces' RequestContext API in the bean's action method to programmatically execute JavaScript in the rendered view.
RequestContext.getCurrentInstance().execute("$('#dialog_id').dialog('close')");
No conditional checks are necessary as the bean's action method won't be invoked anyway when the validation has failed.
Two things
1) Checking for an error in the 'onevent' function
Surely you have a message tag for the mandatory field?
<h:message id="m-my-field-id" for="my-field-id" errorClass="error-class"/>
So you can check for the error-class something like
var message = $('#m-my-field-id');
if(message.hasClass('error-class'){
//do this
}
else{
//do that
}
2) The DOM isn't up to date on success
Yes, I can see the message on the page in Firefox, yet jQuery tells me it is not there.
I have found that using the smallest possible timeout is sufficient to fix this
setTimeout(
function(){
setErrorStyle(source.attr('id'));
},
1
);
I think you should take a look at PrimeFaces' RequestContext. This would help you trigger client-side code on the server side.
#BalusC
in your example code the clientId of the button is not set as a param because it is a AJAX request. So
not empty param[add.clientId] is always false.
But this works:
param['javax.faces.source'] eq add.clientId
(tested with jsf-impl-2.2.12.redhat-1)
regards

Render component with ajax in jsf

The problem is, when I set the render attribute of f:ajax to #form the btnCreateCSV render correctly. But, if I change it to the id of button nothing happen. I wonder to know, how can I solve this problem.
This is my xhtml code :
<h:panelGrid layout="block">
<h:commandButton value="View SQL" action="#{sparqlQueryBean.convert}" id="btnViewSql">
<f:ajax execute="txtQuery btnCreateCSV" render="btnCreateCSV txtSqlQuery" onevent="waiting" listener="#{sparqlQueryBean.generateCommands}"></f:ajax>
</h:commandButton>
<h:commandButton value = "CSV" action = "#{sparqlQueryBean.createCSV}" id = "btnCreateCSV" rendered="#{sparqlQueryBean.showCSV == true}">
<f:ajax execute="#none" render = "#none" onevent="waiting"></f:ajax>
</h:commandButton>
And it's my bean class. In generateCommands method, the value of showCSV set to true. But it dosn't work.
public void generateCommands (AjaxBehaviorEvent event) {
this.setShowCSV(true);
}
With <f:ajax>, JavaScript is used to locate elements in the HTML DOM tree and re-render them. But if a JSF component is not rendered into the HTML output, then there's also nothing in the HTML DOM tree to re-render. You should either re-render its closest parent component which is always rendered instead, or wrap it in another component (e.g. <h:panelGroup>) which is always rendered and re-render it instead.
See also:
Communication in JSF 2 - Ajax rendering of content which is by itself conditionally rendered

Why does my s:selectItems throws no such element exception?

I'm getting this error java.util.NoSuchElementException when i tried to check one of my checkbox under h:selectManycheckBox when i submit the form.
The many checkbox is dynamically populated from the bean. Here is my code.
<h:form id="eF">
<h:inputText id="i" value="#{aklat.suggest}">
<a4j:support event="onkeyup" action="#{aklat.complete}" reRender="m"></a4j:support>
</h:inputText>
<s:div>
<h:selectManyCheckbox value="#{aklat.selectedBooks}" layout="pageDirection" id="m">
<s:selectItems value="#{aklat.books}" var="_book" itemLabel="#{_book}" itemValue="#{_book}" label="#{_book.bookName}"/>
</h:selectManyCheckbox>
<a4j:commandButton value="Add Users" action="#{aklat.fire}"></a4j:commandButton>
</s:div>
</h:form>
The weird part is it renders some data output but when i checked the source code. there are no input type checkbox element.
Is something I am missing.
I assume your managed bean is request scope...
because you are making an ajax request, you have to enable "aklat.books" to persist its value longer than request but shorther than session scope.
If you have tomahawk between your app libraries you can use savestate like this (put it after the h:form tag) :
<t:saveState value="#{aklat.books}"/>
if no tomahawk, you can use a4j:keepAlive:
<a4j:keepAlive beanName = "#{aklat.books}"/>

Resources