How to only update JSF/Primefaces component value upon Ajax sucess, but do nothing on Ajax failure - ajax

I have a JSF front end using Primefaces 5.3 which updates fields dynamically using Ajax. The problem that I am having is that sometimes my Ajax calls fail (ex: server responds with a 500), but my front end is still changing. Essentially, I'm looking to prevent the change of the input field if my ajax fails. Stated differently, I only want the input field to change upon a successful Ajax response.
I'm fairly new to JSF, so I'm not sure how to handle this. In regular HTML/JS, I would have been able to store the value onclick and in my ajax error handler restored the value, but I don't know how to do this using the PF framework.
<div class="Container25">
<p:selectOneRadio id="grid" value="#{cc.attrs.answer.singleAnswer.codeValue}" layout="grid" columns="1" >
<f:selectItems value="#{cc.attrs.menuItems}"
var="item" itemLabel="#{msg[item.code]}" itemValue="#{item.code}" itemLabelEscaped="false"/>
<p:ajax event="change" listener="#{cc.attrs.onChange}" update="#{cc.attrs.update}" disabled="#{cc.attrs.onChange == null }" global="false" />
</p:selectOneRadio>
</div>
I've tried adding the resetValues attribute to the ajax component, but that hasn't helped. Additionally, I've tried adding some custom JS in my onstart handler, but it is undefined.
I figured there must be a simple JSF/PF way of doing this, but can't seem to find it.
How can I either prevent the input value to change until the Ajax call returns successfully (ie: only change the value in the onsuccess handler) or reset my original radio button selection in the event that my Ajax call fails? What do I need to put in my onerror handler to restore the pre-ajax state?

You can use Primefaces RemoteCommand component for an easy solution, just embed it in your form:
<p:remoteCommand name="revertSomeValues"
actionListener="#{relatedBean.revertValuesToDefaults}"
update="componentId" />
And at the bean side you can manipulate the model:
#Named
#ViewScoped
public class relatedBean implements Serializable {
Integer codeValue;
//other model attributes and methods...
public void revertValuesToDefaults() {
setCodeValue(0); //supposing 0 is the default value
//handle other model attributes if needed
}
}
Now you can set the onerror callback alike -> onerror="revertSomeValues()"
You can also update the components wtih Primefaces RequestContext programatically from your bean if needed:
RequestContext context = RequestContext.getCurrentInstance();
context.update("componentId");

Related

When use ajax inside h:commandLink, FacesMessage is not displaying

In jsf. i'm using h:commandLink for adding objects in list. without selecting mandatory fields objects not added in list and showing warning message.its working fine when not using ajax 'render' inside the h:commandLink.
later i decide, i don't want to load my page. so i added ajax inside h:commandLink. but warning message not showing.Please help to fix this problem.
With ajax working:
<h:commandLink value="ADD" action="#{uomGroupBean.goToAddItem}" class="btn-secondary">
<f:ajax render="ITEM_TABLE"></f:ajax>
</h:commandLink>
Without ajax working:
<h:commandLink value="ADD" action="#{uomGroupBean.goToAddItem}" class="btn-secondary"/>
Method for adding:
public String goToAddItem(){
System.out.println("calling......");
if(uomGroup.getBaseUOM()==null){
Util.addWarn("Please select Base UOM");
return null;
}
if(uomGroup.getUomGroupItems()==null || uomGroup.getUomGroupItems().size()==0){
uomGroup.setUomGroupItems(new ArrayList<UomGroupItem>());
}
uomGroup.getUomGroupItems().add(new UomGroupItem());
return "Called";
}
Thanks in advance.

h:inputText value is always null after AJAX event

I use ajax to enable an input text if a certain value of a selectonemenu is selected. Like this:
<a4j:outputPanel id="panelFilial">
<h:selectOneMenu id="perfil" tabindex="5"
value="#{actionCadastrarCotacaoDadosCarga.idProduto}"
label="#{msg.selecione}" style="width: 145px;"
required="false">
<f:selectItems value="#{actionCadastrarCotacaoDadosCarga.listProdutos}"></f:selectItems>
<a4j:support ajaxSingle="true" event="onchange"
action="#{actionCadastrarCotacaoDadosCarga.direcionarEnableOutros}"
onclick="javascript:Richfaces.showModalPanel('progressWaitModalPanel');
atualizarImagem();"
reRender="panelOutros" />
</h:selectOneMenu>
</a4j:outputPanel>
Here's my backing bean method:
public void direcionarEnableOutros() {
if (this.idProduto.equals(ID_PRODUTO_OUTROS)) {
this.enableOutros = false;
this.descricaoProduto = new String();
} else {
this.enableOutros = true;
}
}
When I submit my form, the value of the input text is always null. Am I missing something here?
Here's the input text:
<a4j:outputPanel id="panelOutros">
<h:inputText id="outros" tabindex="6" required="false"
maxlength="50"
value="#{actionCadastrarCotacaoDadosCarga.descricaoProduto}"
disabled="#{!actionCadastrarCotacaoDadosCarga.habilitarCampoOutros}">
</h:inputText>
</a4j:outputPanel>
Assuming you are using Seam, the problem must be the event scope. Change it to conversation scope.
Event Scope
The event (request) context. Spans a server request, from restore view
to render response.
Conversation Scope
The conversation context. Spans multiple requests from the same
browser window, demarcated by #Begin and #End methods. A conversation
context is propagated by any faces request, or by any request that
specifies a conversation id as a request parameter. The conversation
context is not available during the restore view phase.
In JSF 2.x you can make use of #ViewScoped to makee your bean alive while the user interacts with the same view e.g. ajax requests. In JSF 1.x, there's no #ViewScoped, so you had to store and remove the data from view state or even session scope manually. Still, since you're using RichFaces, you can make use of #KeepAlive annotation, which works very similar to #ViewScoped from JSF 2.
Just do this:
#KeepAlive
public class ActionCadastrarCotacaoDadosCarga {
//bean definition here...
}
And make sure the beans is configured in request scope:
<managed-bean-name>actionCadastrarCotacaoDadosCarga</managed-bean-name>
<managed-bean-class>location.of.your.bean.ActionCadastrarCotacaoDadosCarga</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<!-- ^-IMPORTANT-^ -->
</managed-bean>

simulate onclick event picklist primefaces

I know that the primefaces picklist only alows transfer event like
<p:ajax event="transfer" listener="#{bean.onTransfer}" />
But I am looking for an onTargetSelected event. Is there a way to simulate it?
I thought about a JQuery function bound with a click event but I don't know on which element. I saw that when I select a line in the target list, the class of the li is transforming to ui-state-highlight. Is there a way to detect class changing with JQuery?
To call a bean method when the event will be fired, I thought about primefaces remoteCommand to send the ID of my object.
Do you have an idea about this event?
Note: I saw that there is a select with the target values in the source code but the selected value is 'selected' for each item and I don't know if there is something to do with this.
Thanks for your help
I have a trick. I am using this JQuery function :
$(document).ready(function(){
$('.ui-picklist-target .ui-picklist-item td').click(function() {
var id = $(this).closest("li").attr("data-item-value");
$('[id$=selectedItemId]').val(id); // Setting the value of my hidden input
updateSelectedTarget(); // Calling the remoteCommand function
});
});
I have added this to my xhtml page
<h:form>
...
<p:pickList ...>
</p:pickList>
<h:inputHidden id="selectedItemId" value="#{modifierUOBean.selectedTargetId}"/>
<p:remoteCommand name="updateSelectedTarget" actionListener="#{modifierUOBean.onSelectedTarget}"/>
</h:form>
And the bean:
private int selectedTargetId; // and getters and setters
public void onSelectedTarget() {
// Do what you want with selectedTargetId which contains the id of selected item
}

TinyMCE's value in bean on second submit (using jsf.ajax.addOnEvent)

I have set up a basic testcase in which I'm experience some (to me) weird behaviour. When using the setup below, the typed value in the editor will only be visible by h:outputText on the second submit. E.g.
Change value in editor to "myvalue"
Send Ajax-request
h:outputText shows "test" (default value from bean)
Change value in editor to "anothervalue"
Send Ajax-request
h:outputText shows "myvalue"
Send Ajax-request
h:outputText shows "anothervalue"
Note: there's a custom composite, please ask for code if needed (it simply creates textarea for TinyMCE and loads .js file from below)
index.xhtml
<h:body>
<h:form>
<mh:editor id="tinymceEditor"
value="#{bean.value}" />
<h:commandButton value="Ajax">
<f:ajax execute="tinymceEditor"
render="show" />
</h:commandButton>
<h:outputText id="show" value="#{bean.value}" />
</h:form>
</h:body>
jsfhandler.js -> included on header in custom composite mh:editor
jsf.ajax.addOnEvent(function(data) {
switch(data.status) {
case "begin":
tinyMCE.execCommand('mceRemoveControl',true,"tinymceEditor");
tinyMCE.triggerSave();
break;
case "complete":
tinyMCE.execCommand('mceAddControl',true,"tinymceEditor");
break;
case "success":
break;
}
});
Bean.java
#Named
#RequestScoped
public class Bean {
private String value = "test";
}
The JSF ajax begin event is too late in order to take changes in form data into account. The ajax request is already prepared based on form data before this event.
Effectively, the sequence is as follows:
User enters input (and leaves field).
HTML DOM "change" event is triggered on input field.
User clicks submit button.
HTML DOM "click" event is triggered on submit button.
JSF prepares ajax request.
JSF ajax "begin" event is triggered on ajax request.
JSF sends ajax request.
...
Basically, you should be doing tinyMCE.triggerSave() during the HTML DOM "click" event.
<h:commandButton ... onclick="tinyMCE.triggerSave()">
Or, better, during the HTML DOM "change" event of the tinyMCE textarea.

When to use valueChangeListener or f:ajax listener?

What's the difference between the following two pieces of code - with regards to listener placement?
<h:selectOneMenu ...>
<f:selectItems ... />
<f:ajax listener="#{bean.listener}" />
</h:selectOneMenu>
and
<h:selectOneMenu ... valueChangeListener="#{bean.listener}">
<f:selectItems ... />
</h:selectOneMenu>
The valueChangeListener will only be invoked when the form is submitted and the submitted value is different from the initial value. It's thus not invoked when only the HTML DOM change event is fired. If you would like to submit the form during the HTML DOM change event, then you'd need to add another <f:ajax/> without a listener(!) to the input component. It will cause a form submit which processes only the current component (as in execute="#this").
<h:selectOneMenu value="#{bean.value}" valueChangeListener="#{bean.changeListener}">
<f:selectItems ... />
<f:ajax />
</h:selectOneMenu>
When using <f:ajax listener> instead of valueChangeListener, it would by default executed during the HTML DOM change event already. Inside UICommand components and input components representing a checkbox or radiobutton, it would be by default executed during the HTML DOM click event only.
<h:selectOneMenu value="#{bean.value}">
<f:selectItems ... />
<f:ajax listener="#{bean.ajaxListener}" />
</h:selectOneMenu>
Another major difference is that the valueChangeListener method is invoked during the end of the PROCESS_VALIDATIONS phase. At that moment, the submitted value is not been updated in the model yet. So you cannot get it by just accessing the bean property which is bound to the input component's value. You need to get it by ValueChangeEvent#getNewValue(). The old value is by the way also available by ValueChangeEvent#getOldValue().
public void changeListener(ValueChangeEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
// ...
}
The <f:ajax listener> method is invoked during INVOKE_APPLICATION phase. At that moment, the submitted value is already been updated in the model. You can just get it by directly accessing the bean property which is bound to the input component's value.
private Object value; // +getter+setter.
public void ajaxListener(AjaxBehaviorEvent event) {
System.out.println(value); // Look, (new) value is already set.
}
Also, if you would need to update another property based on the submitted value, then it would fail when you're using valueChangeListener as the updated property can be overridden by the submitted value during the subsequent UPDATE_MODEL_VALUES phase. That's exactly why you see in old JSF 1.x applications/tutorials/resources that a valueChangeListener is in such construct been used in combination with immediate="true" and FacesContext#renderResponse() to prevent that from happening. After all, using the valueChangeListener to execute business actions has actually always been a hack/workaround.
Summarized: Use the valueChangeListener only if you need to intercept on the actual value change itself. I.e. you're actually interested in both the old and the new value (e.g. to log them).
public void changeListener(ValueChangeEvent event) {
changeLogger.log(event.getOldValue(), event.getNewValue());
}
Use the <f:ajax listener> only if you need to execute a business action on the newly changed value. I.e. you're actually interested in only the new value (e.g. to populate a second dropdown).
public void ajaxListener(AjaxBehaviorEvent event) {
selectItemsOfSecondDropdown = populateItBasedOn(selectedValueOfFirstDropdown);
}
If you're actually also interested in the old value while executing a business action, then fall back to valueChangeListener, but queue it to the INVOKE_APPLICATION phase.
public void changeListener(ValueChangeEvent event) {
if (event.getPhaseId() != PhaseId.INVOKE_APPLICATION) {
event.setPhaseId(PhaseId.INVOKE_APPLICATION);
event.queue();
return;
}
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
System.out.println(newValue.equals(value)); // true
// ...
}
for the first fragment (ajax listener attribute):
The "listener" attribute of an ajax tag is a method that is called on the server side every time the ajax function happens on the client side. For instance, you could use this attribute to specify a server side function to call every time the user pressed a key
but the second fragment (valueChangeListener) :
The ValueChangeListener will only be called when the form is submitted, not when the value of the input is changed
*you might like to view this handy answer

Resources