+ Start a Discussion
Nicolás KacowiczNicolás Kacowicz 

CSV error while trying to insert more than 1 record, otherwise no error

Hello, I'm trying to insert a CSV file. It's just a simple vsp that I choose a local file to upload and show the data in a table.

I'm trying to insert contacts, the problem is if I try to insert more than 1 contact and if I insert the AccountId field. I know it's a lookup field, I googled and I understood that I have to insert the Account Id instead of the Account Name.

Here is the apex class:

public class FileUploaderContacts
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Contact> conupload; 
    /***This function reads the CSV file and inserts records into the Account object. ***/
    public Pagereference ReadFile()
                //Convert the uploaded file which is in BLOB format into a string
                nameFile =blobToString( contentFile,'ISO-8859-1');
                //Now sepatate every row of the excel file
                filelines = nameFile.split('\n');
                //Iterate through every line and create a Contact record for each row
                conupload = new List<Contact>();
                for (Integer i=1;i<filelines.size();i++)
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                    Contact c = new Contact();
                    c.FirstName = inputvalues[0];
                    c.LastName = inputvalues[1];                    
                    c.Phone = inputvalues[2];     
                    c.AccountId = inputvalues[3];                   
         catch(Exception e){
                 ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
        //Finally, insert the collected records
            insert conupload;
        catch (Exception e)
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
        return null;
   /**** This function sends back to the visualforce page the list of account records that were inserted ****/ 
    public List<Contact> getuploadedContacts()
        if (conupload!= NULL)
            if (conupload.size() > 0)
                return conupload;
                return null;                    
            return null;
         This function convers the input CSV file in BLOB format into a string
        @param input    Blob data representing correct string in @inCharset encoding
        @param inCharset    encoding of the Blob data (for example 'ISO 8859-1')
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);

And here is the Visualforce Page:

<apex:page sidebar="false" controller="FileUploaderContacts" showHeader="false">
   <apex:form >
      <apex:sectionHeader title="Upload Contacts from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <!--  Component to allow user to upload file from local machine -->
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
              <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
      <!-- After the user clicks the 'Upload File' button, this section displays the inserted data -->
      <apex:pageblocktable value="{!uploadedContacts}" var="con" rendered="{!NOT(ISNULL(uploadedContacts))}">
          <apex:column headerValue="Contact First Name">
              <apex:outputField value="{!con.FirstName}"/>
          <apex:column headerValue="Contact last Name">
              <apex:outputField value="{!con.LastName}"/>
          <apex:column headerValue="Phone">
              <apex:outputField value="{!con.Phone}"/>
          <apex:column headerValue="Account">
              <apex:outputField value="{!con.AccountId}"/>

Here is the CSV file:

FirstName ,LastName ,Phone ,AccountId 

I got both of them from http://www.forcetree.com/2010/08/read-and-insert-records-from-csv-file.html and just customized it.


PD: just to be clear, if I insert only 1 contact in the CSV file everything works, and if I insert more than 1 contact without the AccountId field it works.