Tuesday 17 September 2013

AutoSave in Visualforce + Calling an Apex Function from Javascript

AutoSave in Visualforce + Calling an Apex Function from Javascript
I had a couple of Visualforce Page forms. Each form had multiple input boxes for the user to input information.

I had a save button at the top and bottom of
 the page. But still, sometimes the user might accidentally close or navigate to some other page.

Auto Saving
 the page in regular intervals was so nice to have. To do this we will use with  a mix of Javascript and Apex.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWATisBB2IOcVv9w1By1nszVSVNgGzNoeKI2e1qA1kvlYlDZwczcX03fOBin0Jk8Pm8XZE4F790ftbHgAqN3h-P6HYGyXah4RuLmgnj2ElqTpy5zrgqH6Md-3rfEbJqS3unkYEHL58OA/s640/autosave.png

Create a Visualforce Page with the code below.

<apex:page standardController="Account" extensions="savecontroller">
<apex:form >
<apex:pageblock >
<!-- The action function which calles the Apex function 'autosave' -->
<apex:actionFunction name="autosave" action="{!autosave}" rerender="out" status="savestatus"/>

<!-- A status denotion of the update -->
<apex:actionStatus id="savestatus">
          <apex:facet name="start"> Auto Saving....<img src="/img/loading.gif"/> </apex:facet>
</apex:actionStatus>

<apex:pageblocksection columns="2">
      <apex:inputfield value="{!Account.Name}"/>
      <apex:inputfield value="{!Account.BillingCity}"/>
      <apex:inputfield value="{!Account.BillingCountry}"/>
      <apex:inputfield value="{!Account.BillingState}"/>
</apex:pageblocksection>     
</apex:pageblock>

<!-- A javascript recursive function which calls itself every 10 seconds, the setTimeout method calls the apex function 'autosave' defined in the <apex:actionfunction> tag above -->
<script>
          window.setTimeout(recursivecall,10000);
          function recursivecall()
          {
              window.setTimeout(recursivecall,10000);
              autosave();
          }   
</script>
               
</apex:form>     
</apex:page>
Create an Apex Class with the code as given below.
public class savecontroller {
private final Account acct;
    public savecontroller(ApexPages.StandardController controller) {
        this.acct = (Account)controller.getRecord();
    }
    public void autosave()
    {
        update acct;
    }   
}


No comments:

Post a Comment