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

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

Related

commandButton doesn't set correctly f:param if it got a javascript method in onclick event

Between two JSF views xhtmls (both have view scoped backing beans) I would like to pass parameters if the user click a link or a button. If I have an attribute onclick with a JavaScript function to open another page (in this page I would like to use the parameters set in the first page) to the commandButton or commandLink I get the f:param attributes to be \'currentAccess\':\'3\',\'gridNo\':\'5\', and if I don't have an onclick attribute I have it right 'currentAccess':'3','gridNo':'5',
If I have:
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}">
<f:param name="currentAccess" value="#{o.currentAccess}"/>
<f:param name="gridNo" value="#{o.noGrid}"/>
<f:param name="gridCategory" value="#{o.category}"/>
</h:commandButton>
the HTML rendering looks like:
<input type="submit" name="j_idt73:0:j_idt74:j_idt77" value="Ce ai gresit" onclick="mojarra.jsfcljs(document.getElementById('j_idt73:0:j_idt74'),{'j_idt73:0:j_idt74:j_idt77':'j_idt73:0:j_idt74:j_idt77','currentAccess':'1','gridNo':'5','gridCategory':'Drept Procesual Civil'},'');return false" />
which is good, I have access to the parameters (f:viewpara or FacesContext , I use the last one likeFacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("currentAccess"))
BUT
If I have:
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
onclick="confirmGridStatistics('#{strings.doYouWantToSeeTheWrongAnswersInAccessNo} #{o.currentAccess} #{strings.fromDate} #{o.date}?');"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}">
<f:param name="currentAccess" value="#{o.currentAccess}"/>
<f:param name="gridNo" value="#{o.noGrid}"/>
<f:param name="gridCategory" value="#{o.category}"/>
</h:commandButton>
WITH a JavaScript function in onclick event I get the rendering:
<input type="submit" name="j_idt73:2:j_idt74:j_idt77" value="Ce ai gresit" onclick="jsf.util.chain(this,event,'confirmGridStatistics(\'Vrei sa vezi raspunsurile gresite in accessul 3 din data de 16-05-2013?\');','mojarra.jsfcljs(document.getElementById(\'j_idt73:2:j_idt74\'),{\'j_idt73:2:j_idt74:j_idt77\':\'j_idt73:2:j_idt74:j_idt77\',\'currentAccess\':\'3\',\'gridNo\':\'5\',\'gridCategory\':\'Drept Procesual Civil\'},\'\')');return false" />
and in the second views backing bean I get null for the parameters from the FacesContext. Why is that?
UPDATE
I thought that
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().put("currentAccess", access); in the action method whould solve it. But it doesn't, it gives me a java.lang.UnsupportedOperationException
I don't know why this is happening.
I have resolved the my issue with a hack. I still don't know why is the issue described with the parameters.
My solution (I know it`s a hack):
the JavaScipt function among other thing opened my second view (to which I wanted to pass the parameters)
so I have put the parameters (which I want to pass) to the JavaScipt function
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
onclick="confirmGridStatistics('#{strings.doYouWantToSeeTheWrongAnswersInAccessNo} #{o.currentAccess} #{strings.fromDate} #{o.date}?'
, '#{o.currentAccess}', '#{o.noGrid}', '#{o.category}');"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}"/>
and the second view request URL looks like http://myserver:port/access.xhtml?currentAccess=34&noGrid=3&category=category
and in the second view backing bean I access the parameters with
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String currentAccess= request.getParameter("currentAccess");
STILL
If anybody knows why is the initial issue that I would appreciate it to share.
Thank you.

JSF ViewState not updated when submitting 2 forms

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.

primefaces keyup or other ajax event delay

I have something like:
<p:inputText...>
<p:ajax event="keyup" update="somefield" listener="#{someBean.doSomething}"/>
</p:inputText>
But I don't want to do an Ajax request on every keypress, I would like to do the request a half second after the user stops writing.
I have seen this problem solved in jQuery in another question:
How to delay the .keyup() handler until the user stops typing?
I would like to know if it's possible to do this on primefaces or how adapt the solution from the jQuery question.
I'm using PrimeFaces 3.0.M4.
Thank you in advance.
If using Primefaces 5.x, there's a delay attribute in the p:ajax tag for this purpose. So it's done like this:
<p:inputText...>
<p:ajax event="keyup" delay="1000" listener="#{someBean.doSomething}"
update="somefield" process="#this" />
</p:inputText>
If not, you could achieve it using f:ajax instead of p:ajax (yes, it works with p:inputText, too). f:ajax has added support for queue control starting from JSF 2.2. So the code looks like:
<p:inputText...>
<f:ajax event="keyup" delay="1000" listener="#{someBean.doSomething}"
render="somefield" execute="#this" />
</p:inputText>
See also:
Primefaces 5.0 p:ajax javadoc
JSF 2.2 docs for f:ajax
Why don't you use PrimeFaces' RemoteCommand component?
It gives you a global Javascript function, that you can call from wherever whenever you want. And it lets you call the managed-bean method and it has the update attribute for partial update.
<p:inputText id="input" />
<h:form>
<p:remoteCommand name="sendAjaxical" update="somefield" action="#{someBean.doSomething}"/>
</h:form>
Register event handler, I borrowed the following from the same answer you posted:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
jQuery("#input").keyup(function() {
delay(function() { sendAjaxical(); }, 2000); //sendAjaxical is the name of remote-command
});
You cannot use the Primefaces Ajax Component, if you chose the jquery/javascript solution. You would have to implement your own javascript function (with ajax/xmlHttpRequest support) and trigger that function after half a second.
But there is another solution, a workaround: you could use an autocomplete component and use 3 helpful attributes: valueChangeListener(A method expression that refers to a method for
handling a valuchangeevent - you use that instead of completeMethod because you don't need the returning suggestions), queryDelay (Delay to wait in milliseconds before sending
each query to the server) and minQueryLength (Number of characters to be typed before starting
to query - if you don't want to start the ajax request after just one character typed).
I hope you will find this solution quiet interesting...Please see the autocomplete component in action here( http://www.primefaces.org/showcase-labs/ui/autocompleteHome.jsf ) and you can find out more by reading the Primefaces User Guide for 3.0.M4.
A quick hack would be adding a delay in onstart of the p:ajax. Define the following function somewhere in your javascript:
function keyupDelay(request, cfg, delay) {
delay = delay || 2000;// if no delay supplied, two seconds are the default seconds between ajax requests
setTimeout(function() {
cfg.onstart = null;
request.send(cfg)
}, delay);
return false;
}
Basically that function triggers the ajax request in a certain timeout while returning false for the immediate one, and emptying the onstart on that timedout request in order not to stuck in a nasty loop.
Then on the p:ajax:
<p:ajax event="keyup" onstart="return keyupDelay(this, cfg)" />
The delay parameter is optional here, by default it's 2 seconds.

JSF field highlighting with ajax posts?

I'm building on BalusC's solution to highlight and focus fields in JSF. My plan is to output a JSON array with ids and then have a method be called which will process this array. This works fine when I don't use <f:ajax/>
Here is my phase listener solution:
public void beforePhase(PhaseEvent event) {
FacesContext facesContext = event.getFacesContext();
List<String> highlightFields = new ArrayList<String>();
Iterator<String> highlightFieldsItr = facesContext
.getClientIdsWithMessages();
while (highlightFieldsItr.hasNext()) {
StringBuilder sb = new StringBuilder();
sb.append("#");
sb.append(highlightFieldsItr.next().replaceAll(":", "\\\\:"));
highlightFields.add(sb.toString());
}
JSONArray jsonHighlightFields = new JSONArray(highlightFields);
facesContext.getExternalContext().getRequestMap()
.put("errorFields", jsonHighlightFields.toString());
}
Basically this would produce errorFields value with something like ["#some\:id1", "#some\id2"]. Then I can do something like this in my root layout file:
<script>
var errorFields = ${errorFields}; // This will xlate to ["#some\\:id1", "#some\\:id2"
$(document).ready(function(){
processInputErrors(errorFields);
});
</script>
With a processInputErrors function like this:
function processInputErrors(ids) {
for (id in ids) {
if (focus == false) {
jQuery(ids[id]).focus();
focus = true;
}
jQuery(ids[id]).addClass('input-error');
}
}
However, I need to somehow obtain this list in the function which gets called on success of an ajax post.
Now f:ajax does have the onevent attribute and this function does get called, but I'm not sure exactly what it gets passed. How would I be able somehow pass the invalid Ids from the phase listener to this function? It seems to be passed an object which represents the HTMLInputElement?
<f:ajax event="change" onevent="test" render="test test_msg" immediate="true" />
Happy to hear about alternative suggestions or ideas. The goal is basically to focus and highlight the field(s) which are invalid not only on a full post-back but also when using f:ajax.
Thanks!
That article was more targeted on JSF 1.x. JSF 2.x offers now a lot of advantages of which the following are beneficial for your particular requirement:
You can refer the current component in EL by #{component}. In case of input components this is the UIInput which in turn has an isValid() method. This could be used in styleClass attribute.
You can use <f:ajax> to re-render parts of the view, also <script> elements.
1+1 is...
<h:inputText id="input1" value="#{bean.input1}" required="true" styleClass="#{component.valid ? '' : 'error'}">
<f:ajax render="#this input1message focus" />
</h:inputText>
<h:message id="input1message" for="input1" />
...
<h:inputText id="input2" value="#{bean.input2}" required="true" styleClass="#{component.valid ? '' : 'error'}">
<f:ajax render="#this input2message focus" />
</h:inputText>
<h:message id="input2message" for="input2" />
...
<h:panelGroup id="focus"><script>jQuery(":input.error:first").focus();</script></h:panelGroup>
No need for a PhaseListener anymore. You could if necessary wrap the input markup boilerplate in a composite component or a tag file.
Back to your concrete question about the onevent attribute, check this answer: JSF 2: How show different ajax status in same input?

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