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
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()
    {
        try{
                //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];                   
                    
                    conupload.add(c);
                }
         }
         catch(Exception e){
                 ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
                ApexPages.addMessage(errormsg);
         }       
        //Finally, insert the collected records
        try{
            insert conupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }    
        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;
            else
                return null;                    
        else
            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 -->
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
              <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
             </center>  
      
      <!-- 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>
          <apex:column headerValue="Contact last Name">
              <apex:outputField value="{!con.LastName}"/>
          </apex:column>
          <apex:column headerValue="Phone">
              <apex:outputField value="{!con.Phone}"/>
          </apex:column>
          <apex:column headerValue="Account">
              <apex:outputField value="{!con.AccountId}"/>
          </apex:column>
      </apex:pageblocktable> 
      
      </apex:pageBlock>       
   </apex:form>   
</apex:page>

Here is the CSV file:

FirstName ,LastName ,Phone ,AccountId 
John,Doe,099654789,0011I00000CwooBQAR
Jane,Doe,099520,0011I00000Cw6vlQAB

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

Thanks!

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.