primefaces keyup or other ajax event delay - jsf-2

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.

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).

Ajax PrimeFaces not to render the event or disable checkbox

In doc it doesn't have a property render and i did a smoke test by having other components wrapping around p:ajax (Exception: but event attribute is unavailable) am i missing something here?
<p:ajax event="rowSelectCheckbox" listerner="somemethod()" update="someId"/>
Just omit the event totally:
<p:ajax listener="..." update="..."/>
It defaults to event="valueChange" and process="#this", which is often what one want.
If it does'nt work as expected check the Primefaces user guide, find your component and look for "Ajax behavior events" or look for attributes beginning with "on...".
About h:outputLink: its not a Primefaces tag so it should have been f:ajax for this one. However it does'nt work because of this.
Read more in this answer.
rowSelectCheckbox will be use with SelectEvent.
xhtml
<p:ajax event="rowSelectCheckbox" listerner="#{bean.selectCheckbox}" update="someId"/>
managedbean
public void selectCheckbox(SelectEvent event){
}

Event 'onsave' in rich:editor doesn't fire

I'm implementing some kind of frontend editor in my web page, using rich:editor. When clicking a link, the editor should open, and after saving editor's content, the editor should close again. I'm having trouble with onsave event for closing the editor. Here is my code.
This is the link that opens the editor, due to setting the property bean.show to true. It works ok:
<h:commandLink>
...
<f:setPropertyActionListener value="true" target="#{bean.show}" />
</h:commandLink>
This is the editor itself, only rendered when show evaluates to true:
<h:form>
<rich:editor value="..." onsave="showEditor(false)" rendered="#{bean.show}" />
</h:form>
The onsave event should close the editor by setting the show property to false again, but the editor stays open, because showEditor() is not called:
<a4j:jsFunction name="showEditor">
<a4j:param name="param1" assignTo="#{bean.show}" />
</a4j:jsFunction>
Am I doing something completely wrong? Or do you have any other ideas how to realize this? Any help is appreciated.
just double-checked: in version richfaces 4.x, there is no onsave attribute at all, but
oninit
onblur
onfocus
ondirty
onchange
like pointed out in the org.richfaces.component.UIEditor class. The same is true, if you want to use f:ajax to ajaxify the editor.
Right now, the "save"-icon in the editor just sends a form.submit() or something. So either try to add your jsFunction on that event or to introduce an own save-button.
Edit: Richfaces 4 uses the javascript based CKEditor, so if you want to overwrite their "save"-button, this forum entry regarding CKEditor's save implementation might be of your help.
Also a valueChangeListener might be a possibility solution to trigger your Bean.setShow(boolean show) property.
xhtml:
<rich:editor value="#{bean.editorValue}"
valueChangeListener="#{bean.valueChanged}" />
method in managed bean:
public void valueChanged(ValueChangeEvent e) {
// do the code to close the window here
}
The valueChangeListener also works in Richfaces 4.3, but maybe starting within the javascript of the CKEditor is the better choice.
Hope, that helps... L.

Check Tabs visited in p:tabView. Usage of onTabShow Event?

I am trying to track in a controller-bean, which tabs of a p:tabView were already visited (by tab-id).
I don't want to use the onTabChange event for some reasons (blocked already for other things).
So I tried to realize my usecase with onTabShow event of p:tabView. But did not succeed yet. I first tried with p:ajax listener:
<p:tabView>
<p:ajax event="tabShow" listener="#{myBean.checkTab(event)}" .../>
Result was error-message: tabShow not supported in p:ajax ...
Second try was using remoteCommand:
<p:tabView onTabShow="myCommand()">
...
<p:remoteCommand name="myCommand" actionListener="#{myBean.checkTab}" .../>
But how to pass the event as parameter to my bean-method to get the tab-object from?
Does somebody can help or has another idea how I can track the visited tabs in my bean?
With a binding of tabView perhaps? But how?
Thanks!
You can use the <p:ajax/> without specifying an event. That being said, you can get the currently selected tab either by
Binding the activeIndex property on the <p:tabView/> to a backing bean property
<p:tabView activeIndex="#{bean.selectedTabIndex}">
<p:ajax listener="#{myBean.checkTab}" .../>
</p:tabView>
With this variable bound, you can use it in checkTab.
Use the AjaxBehaviorEvent object to access the specific tab selected:
public void checkTab(AjaxBehaviorEvent abe){
TabView tb = (TabView) abe.getComponent();
List<Tab> loadedTabs = tb.getLoadedTabs();
Tab theTab = loadedTabs.get(tb.getActiveIndex());
}
and in your view:
<p:tabView>
<p:ajax listener="#{myBean.checkTab}"/>

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

Resources