Object Records

Object Records Creation Using CSV File | Salesforce Guide

When the records and column values on the CSV file contain quotations, uploading the CSV file to create records becomes complicated. As a result, I devised a simple method for uploading a CSV file and automatically creating custom object data. 

I'll try to walk you through the procedure step by step. 

Step 1: Make a CSV file containing custom object records. 

Step 2: Create a Lightning Web Component 

HTML File:- 

<template> 
    <template if: true={isLoaded}> 
        <lightning-spinner  
            alternative-text="Loading"  
            size="large"> 
        </lightning-spinner> 
    </template> 
    <lightning-card variant="Narrow" icon-name="standard: file" title="File Upload"> 
        <div class="custom-csv-upload-container slds-var-p-horizontal_medium"> 
            <lightning-file-upload  
                accept={acceptedFormats}  
                label="Please upload transactions from the bank download file. Do NOT alter the file before upload."  
                multiple="multiple"  
                onuploadfinished={uploadFileHandler}> 
            </lightning-file-upload> 
        </div> 
    </lightning-card> 
</template>

dont miss out iconDon't forget to check out: Mass/Bulk Insert Custom MetaData Records through CSV | Salesforce Developer Guide

Javascript File:-

import { LightningElement } from 'lwc'; 
import {ShowToastEvent} from 'lightning/platformShowToastEvent'; 
import loadData from '@salesforce/apex/lwcCSVUploaderController.loadData';  
export default class FileUpload extends LightningElement { 
    error; 
    isLoaded = false;  
    get acceptedFormats() { 
        return ['.csv']; 
    } 
    uploadFileHandler( event ) {          
        this.isLoaded = true; 
        const uploadedFiles = event.detail.files;  
        loadData( { contentDocumentId : uploadedFiles[0].documentId } ) 
        .then( result => { 
            this.isLoaded = false; 
            window.console.log('result ===> '+result); 
            this.strMessage = result; 
            this.dispatchEvent( 
                new ShowToastEvent( { 
                    title: 'File Upload Successfully', 
                    message: result, 
                    variant: 'success', 
                    mode: 'sticky' 
                } ), 
            ); 
        }) 
        .catch( error => { 
            this.isLoaded = false; 
            this.error = error; 
            this.dispatchEvent( 
                new ShowToastEvent( { 
                    title: 'Error!!', 
                    message: JSON.stringify( error ), 
                    variant: 'error', 
                    mode: 'sticky' 
                } ), 
            );      
        } )  
    }  
    renderedCallback() { 
        const style = document.createElement('style'); 
        style.innerText = '.custom-csv-upload-contianer .slds-form-element__control{text-align: center;}.custom-csv-upload-contianer .slds-form-element__label{font-weight: bold;text-align: center;display: block;}.custom-csv-upload-contianer .slds-file-selector__body{width: 450px;height: 100px;display: flex;flex-direction: column;justify-content: center;align-items: center;}'; 
        if (this.template.querySelector('.custom-csv-upload-contianer')) 
            this.template.querySelector('.custom-csv-upload-contianer').appendChild(style); 
    } 
}

XML File:-

<?xml version="1.0" encoding="UTF-8"?> 
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> 
    <apiVersion>48.0</apiVersion> 
    <isExposed>true</isExposed> 
    <targets> 
        <target>lightning__AppPage</target> 
        <target>lightning__RecordPage</target> 
        <target>lightning__HomePage</target> 
        <target>lightningCommunity__Page</target> 
        <target>lightningCommunity__Default</target> 
    </targets> 
</LightningComponentBundle>  

dont miss out iconCheck out another amazing blog by Arpit here: System Events in Salesforce - Learn All About it Here

Apex Class:- 

public with sharing class lwcCSVUploaderController { 
    @AuraEnabled 
    public static List<String> loadData(Id contentDocumentId)  {       
        String strMessage; 
        List <Pending_Bank_Deposits__c> pendingBankList = new List <Pending_Bank_Deposits__c>(); 
        //     List<string> records = new List<String>(); 
        List<sObject> listOfSobject = new List<sObject>(); 
        /* if ( contentDocumentId != null ) {  
            csvFileLines = data.tostring().split('\n'); 
        }*/       System.debug('kalsflsf');          
        //  List<String> csvFileLines = new List<String>(); 
        ContentVersion cv = [SELECT Id, ContentDocumentId, VersionData FROM ContentVersion WHERE ContentDocumentId =:ContentDocumentId]; 
        List<String> csvFileLines = cv.VersionData.toString().split('\n'); 
        System.debug('@@records'+csvFileLines);          
        //  Blob data = EncodingUtil.base64Decode(cv.VersionData); //decoded string 
        //get all the rows from the file data 
        //   csvFileLines = data.tostring().split('\n'); 
        List <String> listOfHeaders = csvFileLines[0].split(','); 
        //   List<String> listOfValues = new List<String>(); 
        list<String> listOfHeaderApi = new list<String>(); 
        Set<Integer> clmIndex = new Set<Integer>(); 
        Map<String, Pending_Bank_Deposit1__c> mapB2BCustomSetting = new Map<String, Pending_Bank_Deposit1__c>();        
        Map<String,List<String>> newMap= new Map<String,List<String>>(); 
        List<String> headerValuesCsvFile = new List<String>(csvFileLines[0].trim().split(',')); 
        System.debug('@@headerValuesCsvFile'+headerValuesCsvFile);          
        mapB2BCustomSetting = Pending_Bank_Deposit1__c.getAll(); 
        System.debug('@@mapB2BCustomSetting'+mapB2BCustomSetting); 
        Integer IndexOfHeader=0; 
        //  Map<String,List<String>> mapOfCSV = new Map<String,List<String>>(); 
        //   mapOfCSV.put(records[0],listOfHeaderApi); 
        //  if(mapOfCSV.containsKey()) 
        for(String header : headerValuesCsvFile){ 
            System.debug('@@header'+header); 
            //   headerValues.add(mapB2BCustomSetting.get(headerValue).FieldAPI__c); 
            header = header.removeEnd('\r'); 
            header = header.normalizeSpace();              
            If(mapB2BCustomSetting.containsKey(header)){                  
                listOfHeaderApi.add(mapB2BCustomSetting.get(header).FieldAPI__c); 
                System.debug('@@listOfRecord'+listOfHeaderApi);  
            }  
            else{ 
                listOfHeaderApi.add(''); 
            } 
        } 
        //  List<String> listOfValues = new List<String>(); 
        System.debug('@@listOfRecord'+listOfHeaderApi);       
        for(Integer i = 1; i < csvFileLines.size(); i++){ 
            List<String> inputvalues = csvFileLines[i].split(','); 
            sObject sObj = Schema.getGlobalDescribe().get('Pending_Bank_Deposits__c').newSObject();    
            for(Integer j=0; j<listOfHeaderApi.size(); j++){                                   
                System.debug('demo value of j'+ j); 
                inputvalues[j] = inputvalues[j].remove('\r'); 
                if(inputvalues[j] != '' && inputvalues[j] != null && listOfHeaderApi[j] != '' && listOfHeaderApi[j] != null){ 
                    if(listOfHeaderApi[j] == 'RecordTypeId'){ 
                        Id recordTyeId = Schema.SObjectType.Pending_Bank_Deposits__c.getRecordTypeInfosByName().get(inputvalues[j]).getRecordTypeId(); 
                        sObj.put(listOfHeaderApi[j],recordTyeId) ;  
                    } 
                    else if(listOfHeaderApi[j] == 'Date__c'){ 
                        Date datePendingBankDeposit = date.parse(inputvalues[j]); 
                        sObj.put(listOfHeaderApi[j],datePendingBankDeposit) ;  
                    } 
                    else if(listOfHeaderApi[j] == 'Debit_Amount__c'){ 
                        Double datePendingBankDeposits = double.valueOf(inputvalues[j]); 
                        sObj.put(listOfHeaderApi[j],datePendingBankDeposits) ;  
                    } 
                    else if(listOfHeaderApi[j] == 'Credit_Amount__c'){ 
                        Double amtPendingBankDeposits = double.valueOf(inputvalues[j]); 
                        sObj.put(listOfHeaderApi[j],amtPendingBankDeposits) ;  
                    } 
                    else if(listOfHeaderApi[j] == 'Type__c'){ 
                        String typePendingBankDeposits = String.valueOf(inputvalues[j]); 
                        sObj.put(listOfHeaderApi[j],typePendingBankDeposits) ;                        
                    } 
                    else{ 
                        sObj.put(listOfHeaderApi[j],inputvalues[j]);  
                    }           
                    System.debug('@@sObj'+sObj); 
                }  
            } 
            listOfSobject.add(sObj); 
        } 
        System.debug('@@clmIndex'+clmIndex); 
        System.debug('@@listOfSobject'+listOfSobject); 
        insert listOfSobject; 
        return csvFileLines; 
    }
}

Step 3: Make a lightning tab with the LWC component so you can see what's going on. If creating the tab is too complicated, you can create an Aura Component, nest it within the Aura component, and use it as a tab.  

 

 

Responses

Popular Salesforce Blogs