salesforce Records

How to Get the Failed Records Through Database.Insert/Upsert | Salesforce Developer Guide

Salesforce provides a variety of options for DML. Consider a hypothetical requirement where you need to save the data from a file into your database. Salesforce supports only CSV files, so you need to maintain the format of the file to CSV only. This is your first step.

Now, what to do after you have read the file, there are different ways for both Visualforfce and Aura Lighting Components

For Visualforce you simply use <apex:input> and read file through it, however, in Lightning Component you will use FileReader(). After you have the file data either in a blob (Visualforce Page) or encoded base64 String (in Aura), you need to pass the value in apex.

Header1  Header 2  Header 3  Header 4  Header 5
Data 1 for header 1     Data 1  for header 2    Data 1  for header 3 Data 1  for header 4  Data 1  for header 5 
Data 2 for header 1 Data 2 for header 2 Data 2 for header 3 Data 2 for header 4 Data 2 for header 5

Component:

<div class="select-upload slds-m-left_x-small">
    <lightning:input label="Select File" class="upload-btn select-btn" aura:id="fileId"  onchange="{!c.uploadClaimForm}" type="file" name="filetype"  multiple="false"/>
</div>

dont miss out iconDon't forget to check out: Low-Code Salesforce REST API Integration - All You Need to Know

Controller:

var files = component.find("fileId").get("v.files");
if (files && files.length > 0) {
    var file = files[0];
    var reader = new FileReader();
    reader.onloadend = function() {
        var dataURL = reader.result;
        var content = dataURL.match(/,(.*)$/)[1];
        var fileName = file.name;
        var contentType = file.type;
        var base64Data = content;
        // set your data in an attribute
        component.set("v.encodedUploadedFileData",base64Data);
        //set the file name in a n attribute
        component.set("v.encodedUploadedFileName",fileName);
        //set content type in an attribute
        component.set("v.encodedUploadedFileContenttype",contentType);
    }
    reader.readAsDataURL(file);
}

After you have read the data pass it to the server-side.

Helper:

var action = component.get("c.uploadFile");
action.setParams({
    "parentId": component.get("v.recordId"),
    "fileName": component.get("v.encodedUploadedFileName"),
    "base64Data": component.get("v.encodedUploadedFileData"),
    "contentType":component.get("v.encodedUploadedFileContenttype")
});

Apex Class:

public static void main uploadDataintoDatabase(String parentId, String fileName, String base64Data, String contentType){
    //read you data from the base64Data and create a list for the records from base64Data
    // after you have saved the records in a list named recordsToUpload, you have to save them
    Database.UpsertResult [] listUpsertResult = Database.upsert(recordsToUpload , false);
}

Now, you have inserted or upserted the records in the database, how to know which records have been passed and which have been failed? Again, it is easy to get the success records for whom we can get the Id but what about the error records which do not have id as those? How to know which of them failed. 

dont miss out iconCheck out another amazing blog by Krati here: How to Upload and Show Images in Lightning Aura Component | Salesforce Developer Guide

First, run a loop through your records list, the second loop will iterate through the header values of your file.

for (Integer i = 0; i < recordsToUpload.size(); i++) {
    Database.UpsertResult upsertResultValue = listUpsertResult[i];
    if (!upsertResultValue.isSuccess()) {
        //create csv file data for error records
        for(Database.Error err : upsertResultValue.getErrors()){
            //in case of error, get all the records on that index
            String getEachRecord = '';   
            // header values contains header1, header 2, header 3, heder 4, header 5                    
            for(String headerValue:headerValues){
                if(getEachRecord != null || getEachRecord!=''){                                  
                    getEachRecord =  getEachRecord+ recordsToUpload[i].get(headerValue);
                    getEachRecord = getEachRecord.removeEnd('\n')+',';
                }else{
                    getEachRecord = recordsToUpload[i].get(headerValue)+',';
                }
            }
            //add the reason of error in the string
            String replaceErrorMessage = err.getMessage();
            List<String> errorFields = err.getFields();
            String strErrorFields = String.valueOf(errorFields);
            System.debug('@@err.getFields()'+err.getFields());
            System.debug('@@StrErrorFields'+strErrorFields);
            getEachRecord =  getEachRecord+err.getFields()
            +err.getMessage()
            +'\n';
            getEachRecord = getEachRecord.remove('\r');
            //add the final string in the list
            listRecordsToUploadError.add(getEachRecord);
        }
    }else{
        //create csv file data for success records
        String getEachRecord = '';
        for(String headerValue:headerValues){
            if(getEachRecord != null || getEachRecord!=''){
                getEachRecord =  getEachRecord+ recordsToUpload[i].get(headerValue)+',';
            }else{
                getEachRecord = recordsToUpload[i].get(headerValue)+',';
            }
        }
        getEachRecord = getEachRecord.removeEnd(',');
        getEachRecord =  getEachRecord +'\n';
        getEachRecord = getEachRecord.remove(',,');                                                                                 listRecordstoUploadSuccess.add(getEachRecord);
    }
}

And now you can have the data for the error fields and the success records.

Responses

Popular Salesforce Blogs