Newer Version Available

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

Creating a Record

To create a record using Lightning Data Service, first declare force:recordPreview without assigning a recordId. Then load a record template by calling the getNewRecord function on force:recordPreview. Finally, apply values to the new record, and save the record by calling the saveRecord function on force:recordPreview.
Creating a record with Lightning Data Service is a two-step process.
  1. Call getNewRecord to create an empty record from a record template. This record can be used as the backing store for a form, or otherwise have its values set to data intended to be saved. This is described in a later section.
  2. Call saveRecord to commit the record. This is described in Saving a Record.

Create an Empty Record from a Record Template

To create an empty record from a record template, you must first not set a recordId on the force:recordPreview tag. Without a recordId, Lightning Data Service doesn’t load an existing record.

Then, in your component’s init or another handler, call the getNewRecord on force:recordPreview. getNewRecord takes the following arguments.
Attribute Name Type Description
entityApiName String The entity API name for the sObject of the record to be created.
recordTypeId String The 18 character ID of the record type for the new record.

If not specified, the default record type for the object is used, as defined in the user’s profile.

defaultFieldValues Map A map of field values to set on the empty record before use. Use this attribute to set default or context-specific values.
skipCache Boolean Whether to load the record template from the server, instead of the client-side Lightning Data Service cache. Defaults to false.
callback Function A function invoked after the empty record is created. This function receives no arguments.

getNewRecord doesn’t return a result. It simply prepares an empty record and assigns it to the targetRecord attribute.

Creating a Record

The following example illustrates the essentials of creating a record using Lightning Data Service. This example is intended to be added to an account record Lightning page.

ldsCreate.cmp
1<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
2
3    <aura:attribute name="newContact" type="Object"/>
4    <aura:attribute name="newContactError" type="String"/>
5    <force:recordPreview aura:id="contactRecordCreator"
6        layoutType="FULL"
7        targetRecord="{!v.newContact}"
8        targetError="{!v.newContactError}"
9        />
10
11    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
12
13    <!-- Header -->
14    <div class="slds-page-header" role="banner">
15        <p class="slds-text-heading--label">Create Contact</p>
16    </div>
17
18    <!-- Display Lightning Data Service errors, if any -->
19    <aura:if isTrue="{!not(empty(v.newContactError))}">
20        <div class="recordError">
21            <ui:message title="Error" severity="error" closable="true">
22                {!v.newContactError}
23            </ui:message>
24        </div>
25    </aura:if>
26
27    <!-- Display the new contact form -->
28    <div class="slds-form--stacked">
29
30        <div class="slds-form-element">
31            <label class="slds-form-element__label" for="contactFirstName">First Name: </label>
32            <div class="slds-form-element__control">
33              <ui:inputText class="slds-input" aura:id="contactFirstName"
34                value="{!v.newContact.FirstName}" required="true"/>
35            </div>
36        </div>
37        <div class="slds-form-element">
38            <label class="slds-form-element__label" for="contactLastName">Last Name: </label>
39            <div class="slds-form-element__control">
40              <ui:inputText class="slds-input" aura:id="contactLastName"
41                value="{!v.newContact.LastName}" required="true"/>
42            </div>
43        </div>
44
45        <div class="slds-form-element">
46            <label class="slds-form-element__label" for="contactTitle">Title: </label>
47            <div class="slds-form-element__control">
48              <ui:inputText class="slds-input" aura:id="contactTitle"
49                value="{!v.newContact.Title}" />
50            </div>
51        </div>
52
53        <div class="slds-form-element">
54            <ui:button label="Save Contact" press="{!c.handleSaveContact}"
55                class="slds-button slds-button--brand" />
56        </div>
57
58    </div>
59
60</aura:component>
This component doesn’t set the recordId attribute of force:recordPreview. This tells Lightning Data Service to expect a new record. Here, that’s created in the component’s init handler.
ldsCreateController.js
1({
2    doInit: function(component, event, helper) {
3        // Prepare a new record from template
4        component.find("contactRecordCreator").getNewRecord(
5            "Contact", // sObject type (entity API name)
6            null,      // record type
7            null,      // default record values
8            false,     // skip cache?
9            $A.getCallback(function() {
10                var rec = component.get("v.newContact");
11                var error = component.get("v.newContactError");
12                if(error || (rec === null)) {
13                    console.log("Error initializing record template: " + error);
14                }
15                else {
16                    console.log("Record template initialized: " + rec.sobjectType);
17                }
18            })
19        );
20    },
21
22    handleSaveContact: function(component, event, helper) {
23        if(helper.validateContactForm(component)) {
24            component.set("v.newContact.AccountId", component.get("v.recordId"));
25            component.find("contactRecordCreator").saveRecord(function(saveResult) {
26                if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
27
28                    // Success! Prepare a toast UI message
29                    var resultsToast = $A.get("e.force:showToast");
30                    resultsToast.setParams({
31                        "title": "Contact Saved",
32                        "message": "The new contact was created."
33                    });
34                    resultsToast.fire();
35
36                    // TODO: Reset the form to empty values
37
38                    // Reload the view so components not using force:recordPreview
39                    // are updated
40                    $A.get("e.force:refreshView").fire();
41                }
42                else if (saveResult.state === "INCOMPLETE") {
43                    console.log("User is offline, device doesn't support drafts.");
44                }
45                else if (saveResult.state === "ERROR") {
46                    console.log('Problem saving contact, error: ' +
47                                 JSON.stringify(saveResult.error));
48                }
49                else {
50                    console.log('Unknown problem, state: ' + saveResult.state +
51                                ', error: ' + JSON.stringify(saveResult.error));
52                }
53            });
54        }
55    },
56})
The doInit init handler calls getNewRecord() on the force:recordPreview component, passing in a very simple callback handler. This call creates a new, empty contact record, which is used by the contact form in the component’s markup.

The callback passed to getNewRecord() must be wrapped in $A.getCallback() to ensure correct access context when the callback is invoked. If the callback is passed in without being wrapped in $A.getCallback(), any attempt to access private attributes of your component results in access check failures.

Even if you’re not accessing private attributes, it’s a best practice to always wrap the callback function for getNewRecord() in $A.getCallback(). Never mix (contexts), never worry.

Note

The handleSaveContact handler is called when the Save Contact button is clicked. It’s a straightforward application of saving the contact, as described in Saving a Record, and then updating the user interface.

The helper function, validateContactForm, isn’t shown. It simply validates the form values. For an example of this validation, see Lightning Data Service Example.

Note