[SalesForce] Best practice saving sObject[] in Lightning app

i'm looking for some Lightning advice on saving multiple sObjects in a multi-record editor Lightning app.

I'm using 2 components in the app, an OpportunityLineItem List component and an OpportunityLineItem edit component.

The list component looks something like:

...
<aura:attribute name="olis" type="OpportunityLineItem[]"/>
...
<aura:iteration items="{!v.olis}" var="oli">
    <c:OpportunityLineItemEditRow oli="{!oli}" />
</aura:iteration>
...

A user can make changes to one or more records and then press a save button, which sends the records to the back-end controller and makes the save.

My question:
What would be recommended for this scenario? Have the List component handle the save as [], or let the individual record components handle the save themselves?

The first option might be more efficient, the latter will make error handling easier.

Any links to code for a similar scenario would be appreciated.

Best Answer

Saving an entire list, is probably the better way to do it. You can have a List of Opportunity Line Items, in which you store all of the Line Items that have been edited. Then pass this list to the save method and attempt to save the entire list at once.

<aura:attribute name="olisToSave" type="OpportunityLineItem[]"/>

On edit action:

var olis = component.get("v.olisToSave");
olis.push(thisOli);//or however you add stuff to an sObject Array...
component.set("v.olisToSave", olis);

And finally in the save function:

var action = component.get("c.saveOlis");
action.setParams({
    "olis": component.get("v.olisToSave")
});
$A.enqueueAction(action);

Then in your Apex Controller:

@AuraEnabled
public static void saveOlis(List<OpportunityLineItem> olis){
    update olis;
}
Related Topic