Tuesday 26 November 2013

Inserting Records through Visualforce Page without Apex Dataloader

Here is the way to load your data without using Apex Dataloader or any other third party tool..
Before that create one csv file with the following column names,

--------------------   Download Template from here Contact Template  --------------------------


Apex Class:
  1. public class ContactLoader
  2. {
  3.     //It holdes the Content of the CSV File which you have uploaded.
  4.     public String nameFile{get;set;}
  5.    
  6.     //Rendering pageblocks
  7.     public boolean display{get;set;}
  8.     public boolean records{get;set;}
  9.    
  10.     //Retrieve Content from the CSV File
  11.     public Blob csvFile{get;set;}
  12.    
  13.     //Read Lines from the CSV File
  14.     String[] filelines = new String[]{};
  15.        
  16.         //It hold List of Contact Records
  17.         List<Contact> contactInsert=new List<Contact>();
  18.    
  19.     public ContactLoader()
  20.     {
  21.         display=true;
  22.         records=false;
  23.     }
  24.     public Pagereference ReadFile()
  25.     {
  26.        
  27.         display=false;
  28.         records=true;
  29.        
  30.         if(csvFile!=null)
  31.         {
  32.             // Convert the Blob content to String
  33.             nameFile=csvFile.toString();
  34.            
  35.             //Read the CSV Rows using split method
  36.             filelines = nameFile.split('\n');
  37.         }
  38.         else
  39.         {
  40.             ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Please select a record to upload...!');
  41.             ApexPages.addMessage(errormsg);
  42.         }
  43.        
  44.         try
  45.         {
  46.             for (Integer i=1;i<filelines.size();i++)
  47.             {
  48.                
  49.                 String[] inputvalues = new String[]{};
  50.                    
  51.                     //Read multiple column values within the same row using split method
  52.                     inputvalues = filelines[i].split(',');
  53.                 Contact cnt= new Contact();
  54.                
  55.                 // inputvalues[0] to inputvalues[3] holdes the index of the CSV file,Read and Map Field from CSV to Salesforce.
  56.                
  57.                 //Note : If you want to insert Extra fields map those fields below and in your CSV file
  58.                
  59.                 cnt.FirstName= inputvalues[0];
  60.                 cnt.LastName= inputvalues[1];
  61.                
  62.                 if(String.isNotBlank(inputvalues[2]))
  63.                 {
  64.                     cnt.AccountId= inputvalues[2];
  65.                 }
  66.                 else
  67.                 {
  68.                     cnt.AccountId=null;
  69.                 }
  70.                
  71.                 cnt.LeadSource= inputvalues[3];
  72.                
  73.                 //Add uploaded values into List
  74.                 contactInsert.add(cnt);
  75.             }
  76.            
  77.             //insert your Contact Records into Salesforce
  78.             insert contactInsert;
  79.         }
  80.         catch (Exception e)
  81.         {
  82.             //throw Error if user choosen invalid template
  83.             ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Invalid template or file while processing your records...!');
  84.             ApexPages.addMessage(errormsg);
  85.         }
  86.         return null;
  87.     }
  88.    
  89.     public List<Contact> getuploadedContacts()
  90.     {
  91.        
  92.         //Below function return the inserted records in pageblock table
  93.         set<id> recordid= new set<id>();
  94.         for(contact ct:contactInsert)
  95.         {
  96.             recordid.add(ct.id);
  97.         }
  98.         list<contact> ctctlist=new list <contact>();
  99.         ctctlist=[select FirstName,LastName,AccountId,LeadSource,Account.Name from Contact where id IN: recordid ];
  100.         if (contactInsert!= NULL)
  101.         {
  102.             if (contactInsert.size() > 0)
  103.                 return ctctlist;
  104.            
  105.             else
  106.                 return null;
  107.         }      
  108.         else
  109.         {
  110.             return null;
  111.         }
  112.     }
  113.     public pageReference refresh()
  114.     {
  115.         //redirect after pressed Go Back button
  116.         PageReference pageRef= new PageReference('/apex/UploadContacts');
  117.         pageRef.setRedirect(true);
  118.         return pageRef;
  119.     }
  120. }
Visualforce Page:

  1. <apex:page sidebar="false" controller="ContactLoader" showHeader="false">
  2.     <apex:form >
  3.         <apex:pagemessages />
  4.         <apex:pageBlock title="Upload Your CSV File" rendered="{!display}" >
  5.             <center>
  6.                 Please choose your file to upload : <apex:inputFile value="{!csvFile}" filename="{!nameFile}" /> <br/>
  7.                 <br/><br/><apex:commandButton action="{!ReadFile}" value="Insert" id="theButton" style="background:#216BB5;color:white; width:10%;"/>
  8.             </center>
  9.         </apex:pageBlock>    
  10.         <apex:pageBlock title="Inserted Records" rendered="{!records}">
  11.             <apex:pageblocktable value="{!uploadedContacts}" var="cnt" rendered="{!NOT(ISNULL(uploadedContacts))}">
  12.                 <apex:column headerValue="First Name">
  13.                     <apex:outputField value="{!cnt.FirstName}"/>
  14.                 </apex:column>
  15.                 <apex:column headerValue="Last Name">
  16.                     <apex:outputField value="{!cnt.LastName}"/>
  17.                 </apex:column>
  18.                 <apex:column headerValue="Account Name">
  19.                     <apex:outputField value="{!cnt.Account.Name}"/>
  20.                 </apex:column>
  21.                 <apex:column headerValue="Lead Source">
  22.                     <apex:outputField value="{!cnt.LeadSource}"/>
  23.                 </apex:column>
  24.             </apex:pageblocktable>
  25.             <center>
  26.                 <br/>
  27.                 <apex:commandButton value="Go Back" action="{!refresh}" style="background:#216BB5;color:white;width:10%;"/>
  28.             </center>
  29.         </apex:pageBlock>
  30.     </apex:form>
  31. </apex:page>

Screen Shoots:

Screen 1:


Screen 2:

1 comment:

  1. If my cvs contains a field that is read only for the object, how do I map it? When saving the apex class I get error that field is read only. In my use case I am doing an update to existing record and querying using the external id which is read only. Thanks!

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...