How to create multiple records using the createRecord method in LDS?
Though LDS is typically used to interact with the single record we can use LDS methods to perform DML on multiple records.
In this blog post , we checked how to insert or create a record using createRecord()
using LDS.
Then comes the question, is it possible to insert multiple records using createRecord()
method in LDS? In short, the answer is YES!
We will be using promises in JavaScript to implement it.
Let me walk you through the code.
<template>
<lightning-datatable
key-field="id"
data={data}
columns={columns}
column-widths-mode="fixed">
</lightning-datatable>
</template>
duplicateAccounts.html import {
LightningElement,
track,
wire
} from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountsController.fetchAccounts';
const columns = [{
label: 'Name',
fieldName: 'Name'
},
{
label: 'Type',
fieldName: 'Type'
},
{
label: 'BillingCountry',
fieldName: 'BillingCountry'
},
];
export default class DuplicateAccounts extends LightningElement {
data;
columns = columns;
error;
@wire(fetchAccounts)
wiredAccounts({
error,
data
}) {
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = undefined;
}
}
handleProcessRecords() {
// get the selected rows
var selectedRows = this.template
.querySelector("lightning-datatable")
.getSelectedRows();
// execute all promises
Promise.all(
// loop through all the selected records
selectedRows.map(row => {
// perform the field mapping
const fields = {};
fields[ACCOUNT_NAME_FIELD.fieldApiName] = row.Name;
// specify the object related info
const recordInput = {
apiName: ACCOUNT_OBJECT.objectApiName,
fields
};
// return a promise
return createRecord(recordInput);
})
).then(results => {
// process the results
console.log(results);
}).catch(error => {
console.log(error);
});
}
}
duplicateAccounts.js This approach of using promises to insert multiple records using promises is not suggested unless we are very certain that we will only be dealing with less than 5 - 10 records.
Anyday it's suggested that we use Apex to bulk process the records. Hope this is helpful.