简体   繁体   中英

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM