When I'm uploading an attachment, whole page is getting refreshed. And because of that my form data is getting lost, since file upload is on same page.

I don't want to lose my filled data whenever I upload an attachment.

*****Other form data******

<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" />
<apex:commandButton value="Add File" id="addAttach" action="{!save_attachment}" />

***Controller Method to save attachment.

public static Attachment attachment { 
    get { 
        if (attachment == null) 
            attachment = new Attachment(); 
        return attachment; 
    } set; }

public void save_attachment() { 
    TR1__Application__c acc = [select id from TR1__Application__c Where Id = 'a03410000029mvQ' limit 1]; 
    attachment.parentid = acc.Id;//attId;
    insert attachment; 
    attachment = new Attachment(); 

I have one more button to save form data.

  • Kindly share the code – Samir Nov 8 '16 at 11:43
  • @Samir Please have a look in the code. – SFDC Mafia - VIC Nov 8 '16 at 11:51
  • For action methods, the return type is ideally PageReference, so please try changing void of save_attachment() to PageReference and return null in this method so that it stays on the same page. Pls try it – SF Learner Nov 8 '16 at 22:55

Reference from : Prevent page refresh after upload file in Visualforce

With the current approach, having the commandButton, the form will be automatically submitted to the server and you can't prevent that considering that you want to know whether the upload was successful or not.

A better way of doing that will be to switch to Visualforce Remoting, push the file to the server and manipulate your DOM based on the response. This is a great post that explains how all that ties together - Uploading Attachments to Salesforce using Javascript Remoting

| improve this answer | |
  • Thank you for you suggestion. I have already gone through that link. Just I don't want to do all those Drama, that why I posted it. :) – SFDC Mafia - VIC Nov 8 '16 at 12:09
  • I cant think of other workaround.Do post it here if you figure something and close this question – Samir Nov 8 '16 at 12:11

You can use a simple button instead of Apex:commandbutton and call your actionFunction via that.But first save your form values as a first action then call your save_attachment method.

<button onclick="svFormData();" value="Add File"/> 

<apex:actionFunction name="svFormData" action="{!save_FormData}" oncomplete="svAttc();" rerender="empty"/>
<apex:actionFunction name="svAttc" action="{!save_attachment}" rerender="empty"/>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.