function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Naresh KaneriyaNaresh Kaneriya 

How to replace the old attachment with new attachement?


HI all,
I have "Save Attachment" button On VF page. As I click on "Save Attachment" button  the PDF is Save on Releted List of "Notes & Attachments".
When i Again Click on "Save Attachment" button the New PDF is Save in That Releted List. I want that When Click on Button the Old PDF shoud be Replace with New PDF And Latest PDF should Save. 

My Code

  public PageReference attachPDF() {
        
       List<Attachment>  at = new  List<Attachment> ();
       
        SaveAttachment  = True;
        PageReference pdf =  new PageReference('/apex/PriceSheetScreen'); 
       
        Blob body = pdf.getContentAsPDF();
        Attachment attach = new Attachment( parentId = oppid ,Name = 'PriceSheet.pdf', body =body, IsPrivate = false); 
        insert attach;
        SaveAttachment  = False;
        
        
        
         return null;
          }  


And VF page


<apex:commandButton value="Save Attachment" action="{!attachPDF}" rendered="{!$CurrentPage.Parameters.flatid != null && !SaveAttachment}" style="margin-right:4px;" />
 
shiva pendemshiva pendem
HI Naresh,

Find the code below:

 public PageReference attachPDF() {
         List<Attachment> att=[Select id,name from Attachment where parentId=:oppid ];
         if(att.size()>0)
            Delete acc;
         List<Attachment>  at = new  List<Attachment> ();
         SaveAttachment  = True;
         PageReference pdf =  new PageReference('/apex/PriceSheetScreen'); 
         Blob body = pdf.getContentAsPDF();
         Attachment attach = new Attachment( parentId = oppid ,Name = 'PriceSheet.pdf', body =body, IsPrivate = false); 
         insert attach;
         SaveAttachment  = False;
         return null;
     }  
Hope this will helps you.

Thanks,
Shiva
 
Naresh KaneriyaNaresh Kaneriya
Thanks Shiva For  Reply. 
 List<Attachment> att=[Select id,name from Attachment where parentId=:oppid ];
         if(att.size()>0)
            Delete att;

Its Working fine.