Monday, September 12, 2011

Attach document in Attachment Object using Visualforce page in Salesforce Apex

Hello folks,

We have interesting here...
Today I am going to attach the file to any object related list in attachment object.

Whole code is given below.

You just need to copy and paste this code in your visualforce page.

Note: Please ware in mind you must have an object Id in your VF page URL like

It mean you are calling this VF page by sending the CurrentPage Id which would work as ParentId for the Attachment Object.

VF page:

<apex:page Controller="InputFileAttachment"> 
  <apex:sectionHeader title="Attach File "/>
  <apex:form >
  <apex:pageBlock >
      <apex:pageBlockButtons >
          <apex:commandButton value="Attach New File" action="{!AttachNewFile}"/>

      <apex:pageBlockSection >     
          <apex:inputFile value="{!Attach}"></apex:inputFile>         
Controller :
public class InputFileAttachment {
    public blob Attach {get;set;}  
    string CurrentId ;
    public InputFileAttachment ()
        CurrentId = ApexPages.CurrentPage().getParameters().get('Id');      
    public pagereference AttachNewFile()
        delete [select id from Attachment where ParentId=:CurrentId];
        Blob b = Attach;
        Attachment At = new Attachment(Name ='NewFile'+'.jpg',body = b,parentId=CurrentId);
        insert At;       
        }Catch(Exception ee){}
        return null;

No comments:

Post a Comment