Newer Version Available

This content describes an older version of this product. View Latest

Saving a Record

To save a record using Lightning Data Service, call saveRecord on the force:recordPreview component, and pass in a callback function to be invoked after the save operation completes.
The Lightning Data Service save operation is used in two cases.
  • To save changes to an existing record.
  • To create and save a new record.

To save changes to an existing record, first load the record in EDIT mode. Then call saveRecord on the force:recordPreview component. These techniques are described in the following sections.

To save a new record, and thus create it, first create the record from a record template, as described in Creating a Record. Then call saveRecord on the force:recordPreview component, described in a following section.

Load a Record in EDIT Mode

To load a record that might be updated, set the force:recordPreview tag’s mode attribute to “EDIT”. Other than explicitly setting the mode, loading a record for editing is the same as loading it for any other purpose.

Lightning Data Service records are shared across all components. When you load a record in EDIT mode, the record assigned to the to the targetRecord attribute is a copy of the record object in the Lightning Data Service cache, instead of a direct reference. This protects other components that might also be using the record from unsaved changes in the component that’s editing it. When the edited copy is saved, the “real” version of the record is updated on the server, then the Lightning Data Service cache is updated. At that point, other components using that record are notified of the change.

Note

Call saveRecord to Save Record Changes

To perform the actual save operation, call saveRecord on the force:recordPreview component from the appropriate controller action handler. saveRecord takes one argument, a callback function to be invoked when the operation completes. This callback function receives a SaveRecordResult as its only parameter. SaveRecordResult includes a state attribute that indicates success or error, and other details you can use to handle the result of the operation.

Saving a Record

The following example illustrates the essentials of saving a record using Lightning Data Service. It’s intended for use on a record page. The record ID is supplied by the implicit recordId attribute added by the force:hasRecordId interface.

ldsSave.cmp
1<aura:component
2    implements="flexipage:availableForRecordHome,force:hasRecordId">
3
4    <aura:attribute name="record" type="Object" access="private"/>
5    <aura:attribute name="recordError" type="String" access="private"/>
6
7    <force:recordPreview aura:id="recordHandler"
8      recordId="{!v.recordId}"
9      layoutType="FULL"
10      targetRecord="{!v.record}"
11      targetError="{!v.recordError}"
12      mode="EDIT"
13      />
14
15    <!-- Display a header with details about the record -->
16    <div class="slds-page-header" role="banner">
17        <p class="slds-text-heading--label">Edit Record</p>
18        <h1 class="slds-page-header__title slds-m-right--small
19            slds-truncate slds-align-left">{!v.record.Name}</h1>
20    </div>
21
22    <!-- Display Lightning Data Service errors, if any -->
23    <aura:if isTrue="{!not(empty(v.recordError))}">
24        <div class="recordError">
25            <ui:message title="Error" severity="error" closable="true">
26                {!v.recordError}
27            </ui:message>
28        </div>
29    </aura:if>
30
31    <!-- Display an editing form -->
32    <div class="slds-form--stacked">
33
34        <div class="slds-form-element">
35            <label class="slds-form-element__label" for="recordName">Name: </label>
36            <div class="slds-form-element__control">
37              <ui:inputText class="slds-input" aura:id="recordName"
38                value="{!v.record.Name}" required="true"/>
39            </div>
40        </div>
41
42        <div class="slds-form-element">
43            <ui:button label="Save Record" press="{!c.handleSaveRecord}"
44                class="slds-button slds-button--brand" />
45        </div>
46
47    </div>
48
49</aura:component>
This component loads a record using force:recordPreview set to EDIT mode, and provides a form for editing record values. (In this simple example, just the record name field.)
ldsSaveController.js
1({
2    handleSaveRecord: function(component, event, helper) {
3        component.find("recordHandler").saveRecord($A.getCallback(function(saveResult) {
4            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
5
6                // Saved! Show a toast UI message
7                var resultsToast = $A.get("e.force:showToast");
8                resultsToast.setParams({
9                    "title": "Saved",
10                    "message": "The record was updated."
11                });
12                resultsToast.fire();
13
14                // Reload the view so components not using force:recordPreview
15                // are updated
16                $A.get("e.force:refreshView").fire();
17            }
18            else if (saveResult.state === "INCOMPLETE") {
19                console.log("User is offline, device doesn't support drafts.");
20            }
21            else if (saveResult.state === "ERROR") {
22                console.log('Problem saving record, error: ' +
23                            JSON.stringify(saveResult.error));
24            }
25            else {
26                console.log('Unknown problem, state: ' + saveResult.state +
27                            ', error: ' + JSON.stringify(saveResult.error));
28            }
29        }));
30    },
31
32})
The handleSaveRecord action here is a minimal version. There’s no form validation or real error handling. Whatever is entered in the form is attempted to be saved to the record.