0

I know that I am just missing something on this but I am trying to upsert data via a LWC from a CSV. Currently I am getting an error since we have duplicate rules turned on. All I am trying to do is if that record already exist, it will move on to the next row to insert. What am I missing?

Controller:

public class lwcCSVUploaderController {

@AuraEnabled
public static List<Lead> saveFile(String base64Data) {
    String data    = JSON.deserializeUntyped(base64Data).toString();
    Integer TotalCreated = 0;
    list<Lead> lstCCToUpsert = new list<Lead>();
    list<String> lstCSVLines = data.split('\n');
    list<Lead> dupeList = [Select ID, Email, FirstName, LastName from Lead where Email !=null];

    for(Integer i = 1; i < lstCSVLines.size(); i++){
        Lead ld = new Lead();
        String csvLine = lstCSVLines[i];
        String prevLine = csvLine;
        Integer startIndex;
        Integer endIndex;
        
        while(csvLine.indexOf('"') > -1){
            if(startIndex == null){
                startIndex = csvLine.indexOf('"');
                csvLine = csvLine.substring(0, startIndex) + ':quotes:' + csvLine.substring(startIndex+1, csvLine.length());
            }else{
                if(endIndex == null){
                    endIndex = csvLine.indexOf('"');
                    csvLine = csvLine.substring(0, endIndex) + ':quotes:' + csvLine.substring(endIndex+1, csvLine.length());
                }
            }
            
            if(startIndex != null && endIndex != null){
                String sub = csvLine.substring(startIndex, endIndex);
                sub = sub.replaceAll(',', ':comma:');
                csvLine = csvLine.substring(0, startIndex) + sub + csvLine.substring(endIndex, csvLine.length());
                startIndex = null;
                endIndex = null;
            }
        }
        
        List<String> csvRowData = new List<String>();

        for(String column : csvLine.split(',')){
            column = column.replaceAll(':quotes:', '').replaceAll(':comma:', ',');
            csvRowData.add(column);
        }

        ld.FirstName                      = csvRowData[0];
        ld.LastName                       = csvRowData[1];
        ld.Title                          = csvRowData[2];
        ld.Company                        = csvRowData[3];
        ld.Email                          = csvRowData[4];
        ld.Street                         = csvRowData[5];
        ld.City                           = csvRowData[6];
        ld.State                          = csvRowData[7];
        ld.PostalCode                     = csvRowData[8];
        ld.Industry                       = csvRowData[9];
        ld.Phone                          = csvRowData[10];
        ld.LeadSource                     = csvRowData[11];
        ld.Headquartered_State__c         = csvRowData[12];
        ld.Managing_Director__c           = csvRowData[13];
        ld.Store_Industry__c              = csvRowData[14];
        ld.Industry_Sector__c             = csvRowData[15];
        ld.Ownerid                        = '00G79000000YwYyEAK';
        
            for(Lead newLeads !:dupeList){
                lstCCToUpsert.add(ld);

    }

        //upsert lstCCToUpsert;

    return [Select Id, 
                   FirstName, 
                   LastName, 
                   Company, 
                   Title, 
                   Email,
                   Street, 
                   City, 
                   State, 
                   PostalCode, 
                   Industry, 
                   Phone, 
                   Headquartered_State__c,
                   Managing_Director__c,
                   Store_Industry__c,
                   Industry_Sector__c
                From Lead 
                Where Id in :lstCCToUpsert
            ];
}
}

JS

        import { LightningElement, track, api } from 'lwc';
        import saveFile from '@salesforce/apex/lwcCSVUploaderController.saveFile';
        import {ShowToastEvent} from 'lightning/platformShowToastEvent';

        const columns = [

        { label: 'First Name', fieldName: 'FirstName' },
        { label: 'Last Name', fieldName: 'LastName' },
        { label: 'Title', fieldName: 'Title' },
        { label: 'Company', fieldName: 'Company' },
        { label: 'Email', fieldName: 'Email' },
        { label: 'Street', fieldName: 'Street' },
        { label: 'City', fieldName: 'City' },
        { label: 'State', fieldName: 'State' },
        { label: 'Zip Code', fieldName: 'PostalCode' },
        { label: 'Industry', fieldName: 'Industry' },
        { label: 'Phone', fieldName: 'Phone' }

        ];

        export default class LwcCSVUploader extends LightningElement {

        @api recordid;
        @track columns = columns;
        @track data;
        @track fileName = '';
        @track a
        @track UploadFile = 'Upload CSV File';
        @track showLoadingSpinner = false;
        @track isTrue = false;
        selectedRecords;
        filesUploaded = [];
        file;
        fileContents;
        fileReader;
        content;
        MAX_FILE_SIZE = 1500000;

        handleFilesChange(event) {

            if(event.target.files.length > 0) {
                this.filesUploaded = event.target.files;
                this.fileName = event.target.files[0].name;
            }
        }

        handleSave() {
            if(this.filesUploaded.length > 0) {
                this.uploadHelper();
            }
            else {
                this.fileName = 'Please select a CSV file to upload!!';
            }
        }

        uploadHelper() {
            this.file = this.filesUploaded[0];
            if (this.file.size > this.MAX_FILE_SIZE) {
                window.console.log('File Size is to long');
                return ;
            }

            this.showLoadingSpinner = true;
            this.fileReader= new FileReader();
            this.fileReader.onloadend = (() => {
                this.fileContents = this.fileReader.result;
                this.saveToFile();
            });

            this.fileReader.readAsText(this.file);
        }

        saveToFile() {
            saveFile({ base64Data: JSON.stringify(this.fileContents), cdbId: this.recordid})
            .then(result => {
                window.console.log('result ====> ');
                window.console.log(result);
                this.data = result;
                this.fileName = this.fileName + ' - Uploaded Successfully';
                this.isTrue = false;
                this.showLoadingSpinner = false;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success!!',
                        message: this.file.name + ' - Uploaded Successfully!!!',
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                window.console.log(error);
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error while uploading File',
                        message: error.message,
                        variant: 'error',
                    }),
                );
            });
        }
        }

Template

        <template>
            
            <template if:true={showLoadingSpinner}>
                <div style="z-index: 10000 !important;">
                    <lightning-spinner alternative-text="Uploading......" size="medium" style="z-index: 10000 !important;"></lightning-spinner>
                </div>
            </template>

            <lightning-card title="Process CSV File">

                <div style="margin-left:4%; margin:0px auto; width: 300px;">
                    <div>
                        <lightning-input label="" name="file uploader" onchange   ={handleFilesChange} type="file" multiple></lightning-input>
                    </div><br/>
                    <div class="slds-text-body_small slds-text-color_error">{fileName}

                    </div><br/>
                    <div>
                        <lightning-button class="slds-m-top--medium" label={UploadFile} onclick  ={handleSave} variant="brand" disabled={isTrue}></lightning-button>
                    </div>
                </div><br/><br/>


            </lightning-card>
            
            <lightning-card title="Leads" icon-name="standard:lead">
                <div style="width: auto;">
                    <template if:true={data}>
                            <lightning-datatable
                                    data={data}
                                    columns={columns}
                                    key-field="id">
                            </lightning-datatable>
                    </template>
                </div>
            </lightning-card>



        </template>

1 Answer 1

1

Use the alternative Database.upsert method:

Database.UpsertResult[] results = Database.upsert(lstCCToUpsert, false);

The second parameter, false, allows a partial success. You can parse the results array to determine which records failed, in case you want to report errors to the user.

Also, having very recently done a CSV parser myself, I recommend parsing the CSV on the client, converting that CSV into an array of objects:

[
  { sobjectType: 'Lead',
    FirstName: 'Brian',
    LastName: 'Fear',
    Email: 'donotreply@salesforce.com',
    // ... etc
  },
  // ... etc
]

Then, you can change your Apex code to just:

public class Result {
  @AuraEnabled public Boolean success { get; set; }
  @AuraEnabled public String error { get; set; }
}
@AuraEnabled public static Result[] saveFile(Lead[] records) {
  Database.UpsertResult[] results = Database.upsert(records, false);
  // Do error handling here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.