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
shobana shobanashobana shobana 

Provision to attach a new attachment!!!

Hi everyone,
   
I need to upload new attachment to opportunity,
If I click on New Attachment button( first Visualforce page ) , it redirects to other Visualforce and provision to choose file and click upload, then the attachment appears in first Visualforce page.
I  am not getting any error but functionality is not working..
Actually when i am clicking on Choosefile button on second visualforce page we can choose a file but the thing is while am clicking the upload button i want to show the chosen file in first visualforce.

 
How do I do that?

I wrote some code below, and I attached screenshots below.
 First visualfore page:
User-added image
My Second visualforce page:
User-added image
my visualfore page-1
<apex:page standardController="opportunity" extensions="FileUploadController">
  <apex:form >
        <apex:pageblock >
            <apex:pageBlockSection title="Attachments" columns="1">
            <apex:CommandButton value="New Attachment" action="{!attach_new}"/>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form> 
</apex:page>


Visualforce page-2


<apex:page standardController="Opportunity" extensions="FileUploadController" showHeader="true">
<apex:pageBlock id="Pid">
    <apex:pageBlockSection title="Select a file to be uploaded" collapsible="false"/>
</apex:pageBlock>
    <apex:outputPanel id="panel_Upload">
    <apex:form id="form_Upload">
        <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
        <apex:actionRegion >
            <apex:commandButton id="button_Upload" value="Upload" action="{!processUpload}"/>
        </apex:actionRegion>
        <apex:CommandButton value="Cancel" action="{!Cancel}"/>
    </apex:form>
    </apex:outputPanel>
    <apex:pageBlock id="BId">
        <apex:pageBlockSection >
            <apex:dataTable Value="{!la}" var="l">
                <apex:column value="{!l.Name}"/>
            </apex:dataTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
</apex:page>


My controller:

public class FileUploadController {
Public Opportunity opp{get; set;}
    private String fileName;
    private Integer fileSize; 
    private Blob fileBody; 
    public FileUploadController(ApexPages.StandardController controller) { } 
    public String getFileName() {
         return this.fileName; 
    } 
    
    public void setFileName(String fileName) { 
        this.fileName = fileName; 
    } 
    public Blob getFileBody() {
        return this.fileBody; 
    }
    
    public void setFileBody(Blob fileBody) {
        this.fileBody = fileBody; 
        setFileSize(this.fileBody.size()); 
    } 
    
    public Integer getFileSize() { 
        return this.fileSize;
    } 
    
    public void setFileSize(Integer fileSize) { 
        this.fileSize = fileSize; 
    } 
    
    List<Attachment> la{get;set;}
    
    Public List<Attachment> getLa(){
        return la;
    }
    
    private Database.SaveResult insertCustomObject() { 
        Opportunity custObj = new Opportunity(); 
        custObj.Name= 'Ranjith';
        insert la;
        return Database.insert(custObj); 
    }
    private Database.SaveResult insertAttachment(Id parentId) {
        Database.SaveResult result; 
        Attachment attachment = new Attachment(); 
        attachment.Body = this.fileBody; 
        attachment.Name = this.fileName; 
        attachment.ParentId = parentId; 
        result = Database.insert(attachment); 
        fileBody = Blob.valueOf(' '); 
        return result; 
    } 
    
    public Void processUpload() {
        try { 
            Database.SaveResult result = insertCustomObject();
            result = insertAttachment(result.getId());  
           } catch (Exception e) {
                ApexPages.AddMessages(e);
           } 
   }
    public pagereference attach_new(){
                pagereference pag = new pagereference('/apex/NewAttachments');
                return pag;
    } 
}
Anyone help me out solve this scenario.
Thank you in advance...
 
Best Answer chosen by shobana shobana
Himanshu ParasharHimanshu Parashar
Hi Shobana,

There are many mistakes you were doing in the code but you were not able to see them because they were coming in debug log.

Let me summarize some issues first which your code have :

1. Close date and stagename is always required while creating the opportunity. those were missing at line 80
2. Until and unless we don't have any parent object for attachment. attachement can't  be inserted.
3. There was no code written to redirect back on you fileupload page.
4. Action region was used on page.

Here is the rectified version of your code Please have a look and try to understand the code


File Uplaod VF page
<apex:page standardController="opportunity" extensions="FileUploadController">
  <apex:form >
        <apex:pageblock >
            <apex:pageBlockSection title="Attachments" columns="1">
            <apex:CommandButton value="New Attachment" action="{!attach_new}"/>
            </apex:pageBlockSection>
            
            <!-- Code to show attachment -->        
            <apex:pageBlockTable value="{!attachments}" var="item">
                <apex:column value="{!item.name}"/> 
            </apex:pageBlockTable> 
        </apex:pageblock>
        
        
    </apex:form> 
</apex:page>


NewAttachment VF Page
 
<apex:page standardController="Opportunity" extensions="FileUploadController" showHeader="true">
<apex:pageBlock id="Pid">
    <apex:pageBlockSection title="Select a file to be uploaded" collapsible="false"/>
</apex:pageBlock>
    <apex:outputPanel id="panel_Upload">
    <apex:form id="form_Upload">
        
        <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
          <!-- Action Region removed -->
            <apex:commandButton id="button_Upload" value="Upload" action="{!processUpload}"/>
          
        <apex:CommandButton value="Cancel" action="{!Cancel}"/>
    </apex:form>
    </apex:outputPanel>
    <apex:pageBlock id="BId">
        <apex:pageBlockSection >
            <apex:dataTable Value="{!la}" var="l">
                <apex:column value="{!l.Name}"/>
            </apex:dataTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
</apex:page>


Controller:
 
public class FileUploadController {
    Public Opportunity opp;
    private String fileName;
    private Integer fileSize; 
    private Blob fileBody; 
    public FileUploadController(ApexPages.StandardController controller)
    {
        this.opp=(Opportunity)controller.getrecord();
        
    } 
    
   public Opportunity getOpp() {
      if(opp== null)
      {
        opp= new Opportunity();
      }
      return Opp;
   }
    
    public String getFileName() {
         return this.fileName; 
    } 
    
    public void setFileName(String fileName) { 
        this.fileName = fileName; 
    } 
    public Blob getFileBody() {
        return this.fileBody; 
    }
    
    public void setFileBody(Blob fileBody) {
        this.fileBody = fileBody; 
        setFileSize(this.fileBody.size()); 
    } 
    
    public Integer getFileSize() { 
        return this.fileSize;
    } 
    
    public void setFileSize(Integer fileSize) { 
        this.fileSize = fileSize; 
    } 
    
    List<Attachment> la{get;set;}
    
    Public List<Attachment> getLa(){
        return la;
    }
    
    private void insertCustomObject() { 
        opp.Name= 'Ranjith';
        opp.stagename='1st Stage';  // Defined
        opp.closedate=system.today(); // Defined
        upsert opp;
    }
    private Database.SaveResult insertAttachment(Id parentId) {
        Database.SaveResult result; 
        Attachment attachment = new Attachment(); 
        attachment.Body = this.fileBody; 
        attachment.Name = this.fileName; 
        attachment.ParentId = parentId; 
        result = Database.insert(attachment); 
        fileBody = Blob.valueOf(' '); 
        return result; 
    } 
    
    public pagereference processUpload() {
        try { 
            insertCustomObject();
            Database.SaveResult result = insertAttachment(opp.id);  
            
           } catch (Exception e) {
                ApexPages.AddMessages(e);
           } 
           pagereference pag = new pagereference('/apex/fileupload?id=' + opp.id); //defined
           pag.setredirect(true);
           return pag;

   }
    public pagereference attach_new(){
                return Page.NewAttachments;
               
    } 
    
    /******This Code will show existing attachment after upload or if ID Passed
    public Attachment[] attachments {
    get {
            if(opp.id!=null)
            { 
            if (attachments == null) {

                attachments = [
                    select Id, Name, Description, LastModifiedDate
                    from Attachment
                    where ParentId = :opp.id
                    order by Name
                    ];
                }
            
            }
        
        return attachments;
    }
    private set;
    }

}



Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.



 

All Answers

Himanshu ParasharHimanshu Parashar
Hi Shobana,

There are many mistakes you were doing in the code but you were not able to see them because they were coming in debug log.

Let me summarize some issues first which your code have :

1. Close date and stagename is always required while creating the opportunity. those were missing at line 80
2. Until and unless we don't have any parent object for attachment. attachement can't  be inserted.
3. There was no code written to redirect back on you fileupload page.
4. Action region was used on page.

Here is the rectified version of your code Please have a look and try to understand the code


File Uplaod VF page
<apex:page standardController="opportunity" extensions="FileUploadController">
  <apex:form >
        <apex:pageblock >
            <apex:pageBlockSection title="Attachments" columns="1">
            <apex:CommandButton value="New Attachment" action="{!attach_new}"/>
            </apex:pageBlockSection>
            
            <!-- Code to show attachment -->        
            <apex:pageBlockTable value="{!attachments}" var="item">
                <apex:column value="{!item.name}"/> 
            </apex:pageBlockTable> 
        </apex:pageblock>
        
        
    </apex:form> 
</apex:page>


NewAttachment VF Page
 
<apex:page standardController="Opportunity" extensions="FileUploadController" showHeader="true">
<apex:pageBlock id="Pid">
    <apex:pageBlockSection title="Select a file to be uploaded" collapsible="false"/>
</apex:pageBlock>
    <apex:outputPanel id="panel_Upload">
    <apex:form id="form_Upload">
        
        <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
          <!-- Action Region removed -->
            <apex:commandButton id="button_Upload" value="Upload" action="{!processUpload}"/>
          
        <apex:CommandButton value="Cancel" action="{!Cancel}"/>
    </apex:form>
    </apex:outputPanel>
    <apex:pageBlock id="BId">
        <apex:pageBlockSection >
            <apex:dataTable Value="{!la}" var="l">
                <apex:column value="{!l.Name}"/>
            </apex:dataTable>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
</apex:page>


Controller:
 
public class FileUploadController {
    Public Opportunity opp;
    private String fileName;
    private Integer fileSize; 
    private Blob fileBody; 
    public FileUploadController(ApexPages.StandardController controller)
    {
        this.opp=(Opportunity)controller.getrecord();
        
    } 
    
   public Opportunity getOpp() {
      if(opp== null)
      {
        opp= new Opportunity();
      }
      return Opp;
   }
    
    public String getFileName() {
         return this.fileName; 
    } 
    
    public void setFileName(String fileName) { 
        this.fileName = fileName; 
    } 
    public Blob getFileBody() {
        return this.fileBody; 
    }
    
    public void setFileBody(Blob fileBody) {
        this.fileBody = fileBody; 
        setFileSize(this.fileBody.size()); 
    } 
    
    public Integer getFileSize() { 
        return this.fileSize;
    } 
    
    public void setFileSize(Integer fileSize) { 
        this.fileSize = fileSize; 
    } 
    
    List<Attachment> la{get;set;}
    
    Public List<Attachment> getLa(){
        return la;
    }
    
    private void insertCustomObject() { 
        opp.Name= 'Ranjith';
        opp.stagename='1st Stage';  // Defined
        opp.closedate=system.today(); // Defined
        upsert opp;
    }
    private Database.SaveResult insertAttachment(Id parentId) {
        Database.SaveResult result; 
        Attachment attachment = new Attachment(); 
        attachment.Body = this.fileBody; 
        attachment.Name = this.fileName; 
        attachment.ParentId = parentId; 
        result = Database.insert(attachment); 
        fileBody = Blob.valueOf(' '); 
        return result; 
    } 
    
    public pagereference processUpload() {
        try { 
            insertCustomObject();
            Database.SaveResult result = insertAttachment(opp.id);  
            
           } catch (Exception e) {
                ApexPages.AddMessages(e);
           } 
           pagereference pag = new pagereference('/apex/fileupload?id=' + opp.id); //defined
           pag.setredirect(true);
           return pag;

   }
    public pagereference attach_new(){
                return Page.NewAttachments;
               
    } 
    
    /******This Code will show existing attachment after upload or if ID Passed
    public Attachment[] attachments {
    get {
            if(opp.id!=null)
            { 
            if (attachments == null) {

                attachments = [
                    select Id, Name, Description, LastModifiedDate
                    from Attachment
                    where ParentId = :opp.id
                    order by Name
                    ];
                }
            
            }
        
        return attachments;
    }
    private set;
    }

}



Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.



 
This was selected as the best answer
shobana shobanashobana shobana
Hi  Himanshu Parashar

Thank you for giving me reply.Its working good.
But the thing before showing the result it shows User-added image 
Actually i have changed my class as fileupload.
Can you please explain  why am getting this error.
 
Himanshu ParasharHimanshu Parashar
Hi Shobana,

at line 75 in controller replace pageupload with your first pagename. I was using fileupload as vf page name.

Thanks,
Himanshu
shobana shobanashobana shobana
Hi 
Himanshu Parashar

Thank you for giving reply and  its working good...........
shobana shobanashobana shobana
Hi Himanshu Parashar
For the same concept i want to show the checkbox and remove button  in my first visualforce page
in order to remove the attachments.for that i used wrapper class concept.But i took a seperate method for remove action.How to show both remove action and attachments in single pageblock table.
Just give me guidelines..
my controller
public class FileUpload {
        //for wrapper class
    Public list<wrapperclass> listwrapper{get;set;}
    

        //for attachment
    Public Opportunity opp;
    private String fileName;
    private Integer fileSize;
    private Blob fileBody;
    public FileUpload(ApexPages.StandardController controller){
        
        this.opp=(Opportunity)controller.getrecord();
        //for wrapper class concept
               listwrapper=new list<wrapperclass>();
               list<Opportunity> O=[select id,name,
                              (select id,name,description 
                               from Attachments)
                             from Opportunity];
               if(!O.IsEmpty()){
               for(Attachment k:O[0].Attachments)
               {
               listwrapper.add(new wrapperclass(k));
               }
               }
         

    }

          // for wrapper class 
        Public class wrapperclass {
            public boolean checked{get;set;}
            public Attachment k{get;set;}
            public wrapperclass(Attachment k){
            this.k=k;
            }
            }
        Public pageReference Remove()
        {
        list<Attachment> listtobedelete = new list<Attachment>();
        if(!listwrapper.IsEmpty()){
            for(Integer i=0;i<listwrapper.size();i++)
            {
            Wrapperclass w = listwrapper[i];
            if(w.checked==true){
            listtobedelete.add(w.k);
            listwrapper.remove(i);
            Delete listtobedelete;
            i--;
            }
            }
            }
            if(listtobedelete.IsEmpty())
            {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Select atleast one column '));
            }
            
            return null;
            }
         

   public Opportunity getOpp() {

      if(opp== null)

      {

        opp= new Opportunity();

      }

      return Opp;

   }
     

    public String getFileName() {

         return this.fileName;

    }

     

    public void setFileName(String fileName) {

        this.fileName = fileName;

    }

    public Blob getFileBody() {

        return this.fileBody;

    }

     

    public void setFileBody(Blob fileBody) {

        this.fileBody = fileBody;

        setFileSize(this.fileBody.size());

    }

     

    public Integer getFileSize() {

        return this.fileSize;

    }

     

  public void setFileSize(Integer fileSize) {

        this.fileSize = fileSize;

    }

     

    List<Attachment> la{get;set;}

     

    Public List<Attachment> getLa(){

        return la;

    }

     

    private void insertCustomObject() {
        opp.Name= 'Ranjith';

        opp.stagename='1st Stage';  // Defined

        opp.closedate=system.today(); // Defined

        upsert opp;

    }

    private Database.SaveResult insertAttachment(Id parentId) {

        Database.SaveResult result;

        Attachment attachment = new Attachment();

        attachment.Body = this.fileBody;

        attachment.Name = this.fileName;

        attachment.ParentId = parentId;

        result = Database.insert(attachment);

        fileBody = Blob.valueOf(' ');
        return result;

    }

   

    public pagereference processUpload() {

        try {

            insertCustomObject();

            Database.SaveResult result = insertAttachment(opp.id); 

             

           } catch (Exception e) {

                ApexPages.AddMessages(e);

           }

           pagereference pag = new pagereference('/apex/visualforcepage1?id=' + opp.id); //defined

         pag.setredirect(true);

           return pag;

 

   }

    public pagereference attach_new(){

                return Page.visualforcepage2;

                

    }
    

     

    //This Code will show existing attachment after upload or if ID Passed

    public Attachment[] attachments {

    get {

            if(opp.id!=null)

            {

            if (attachments == null) {

 
                attachments = [

                    select Id, Name, Description, LastModifiedDate

                    from Attachment

                    where ParentId = :opp.id

                    order by Name

                    ];

                }

             

            }

         

        return attachments;

    }

    private set;

    }

 

}

Thank you in advance..