Newer Version Available
Creating a Record
Create a Record using lightning:recordForm
To create a record using lightning:recordForm, leave out the recordId attribute.
This example displays a form that creates an account record with a list of fields. The Cancel and Save buttons are displayed at the bottom of the form.
1<aura:component>
2 <aura:attribute name="fields"
3 type="String[]"
4 default="['Name', 'Industry']"/>
5 <lightning:recordForm objectApiName="Account"
6 fields="{!v.fields}"/>
7</aura:component>When the record saves successfully, the fields display pencil icons to denote that inline editing is available. This view is displayed until you refresh or reload the page. Then the form redisplays the record fields without data, ready to create a new record.
Alternatively, use the Full layout type, which loads all fields from the full layout to display a form that creates a record. The columns attribute displays the record fields in two columns that are evenly sized.
1<aura:component>
2 <lightning:recordForm objectApiName="Account"
3 layoutType="Full"
4 columns="2"/>
5</aura:component>Customize Error Handling in lightning:recordForm
When an error is encountered during save, lightning:recordForm displays an error message at the top of the form. You can provide additional error handling using the onerror event handler.
This example displays a toast message when an error is returned.
1<aura:component>
2 <aura:attribute name="fields"
3 type="String[]"
4 default="['Name', 'Industry']"/>
5
6 <!-- Displays toast notifications -->
7 <lightning:notificationsLibrary aura:id="notifLib" />
8 <lightning:recordForm
9 objectApiName="Account"
10 fields="{!v.fields}"
11 onerror="{!c.handleError}"/>
12</aura:component>To return the error message, use event.getParam("message").
1({
2 handleError: function (cmp, event, helper) {
3 cmp.find('notifLib').showToast({
4 "title": "Something has gone wrong!",
5 "message": event.getParam("message"),
6 "variant": "error"
7 });
8 }
9})To customize the form behavior when a record saves successfully, use the onsuccess event handler.
If you want to provide a custom layout or load custom field values when the form displays, use the lightning:recordEditForm component as shown in the next section.
Create a Record with a Custom Layout Using lightning:recordEditForm
To provide a custom layout for your form fields, use the lightning:recordEditForm component.
Pass in the fields to lightning:inputField, which displays an input control based on the record field type.
This example creates a custom layout using the Grid utility classes in Lightning Design System.
1<aura:component>
2 <lightning:recordEditForm objectApiName="Account">
3 <lightning:messages />
4 <div class="slds-grid">
5 <div class="slds-col slds-size_2-of-3">
6 <lightning:inputField fieldName="Name"/>
7 </div>
8 <div class="slds-col slds-size_1-of-3">
9 <lightning:inputField fieldName="Industry"/>
10 </div>
11 </div>
12 <lightning:button class="slds-m-top_small" type="submit" label="Create new" />
13 </lightning:recordEditForm>
14</aura:component>When a server error is encountered,lightning:recordEditForm displays an error message above the form fields. To enable automatic error handling, include the lightning:messages component. Alternatively, provide your own error handling using the onerror event handler.
Another feature that lightning:recordEditForm provides that’s not available with lightning:recordForm is preset custom field values, as shown in the next section.
Prepopulate Field Values
To provide a custom field value when the form displays, use the value attribute on lightning:inputField. If you're providing a record ID, the value returned by the record on load does not override this custom value.
Alternatively, set the field value using this syntax.
1cmp.find("nameField").set("v.value", "My New Account Name");If you require more customization when creating a record than what lightning:recordForm and lightning:recordEditForm allow, consider using force:recordData.
Create a Record via a Custom User Interface Using force:recordData
- Call getNewRecord to create an empty record from a record template. You can use this record as the backing store for a form or otherwise have its values set to data intended to be saved.
- Call saveRecord to commit the record. This is described in Editing and Saving a Record.
Create an Empty Record from a Record Template
To create an empty record from a record template, you can’t set a recordId on the force:recordData tag. Without a recordId, Lightning Data Service doesn’t load an existing record.
| Attribute Name | Type | Description |
|---|---|---|
| objectApiName | String | The object API name for the new record. |
| 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. |
| 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.
1<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId">
2
3 <aura:attribute name="newContact" type="Object"/>
4 <aura:attribute name="simpleNewContact" type="Object"/>
5 <aura:attribute name="newContactError" type="String"/>
6
7 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
8
9 <force:recordData aura:id="contactRecordCreator"
10 layoutType="FULL"
11 targetRecord="{!v.newContact}"
12 targetFields="{!v.simpleNewContact}"
13 targetError="{!v.newContactError}" />
14
15 <!-- Display the new contact form -->
16 <div class="Create Contact">
17 <lightning:card iconName="action:new_contact" title="Create Contact">
18 <div class="slds-p-horizontal--small">
19 <lightning:input aura:id="contactField" label="First Name" value="{!v.simpleNewContact.FirstName}"/>
20 <lightning:input aura:id="contactField" label="Last Name" value="{!v.simpleNewContact.LastName}"/>
21 <lightning:input aura:id="contactField" label="Title" value="{!v.simpleNewContact.Title}"/>
22 <br/>
23 <lightning:button label="Save Contact" variant="brand" onclick="{!c.handleSaveContact}"/>
24 </div>
25 </lightning:card>
26 </div>
27
28 <!-- Display Lightning Data Service errors -->
29 <aura:if isTrue="{!not(empty(v.newContactError))}">
30 <div class="recordError">
31 {!v.newContactError}</div>
32 </aura:if>
33
34</aura:component>1({
2 doInit: function(component, event, helper) {
3 // Prepare a new record from template
4 component.find("contactRecordCreator").getNewRecord(
5 "Contact", // sObject type (objectApiName)
6 null, // recordTypeId
7 false, // skip cache?
8 $A.getCallback(function() {
9 var rec = component.get("v.newContact");
10 var error = component.get("v.newContactError");
11 if(error || (rec === null)) {
12 console.log("Error initializing record template: " + error);
13 return;
14 }
15 console.log("Record template initialized: " + rec.apiName);
16 })
17 );
18 },
19
20 handleSaveContact: function(component, event, helper) {
21 if(helper.validateContactForm(component)) {
22 component.set("v.simpleNewContact.AccountId", component.get("v.recordId"));
23 component.find("contactRecordCreator").saveRecord(function(saveResult) {
24 if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
25 // record is saved successfully
26 var resultsToast = $A.get("e.force:showToast");
27 resultsToast.setParams({
28 "title": "Saved",
29 "message": "The record was saved."
30 });
31 resultsToast.fire();
32
33 } else if (saveResult.state === "INCOMPLETE") {
34 // handle the incomplete state
35 console.log("User is offline, device doesn't support drafts.");
36 } else if (saveResult.state === "ERROR") {
37 // handle the error state
38 console.log('Problem saving contact, error: ' + JSON.stringify(saveResult.error));
39 } else {
40 console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));
41 }
42 });
43 }
44 }
45})The handleSaveContact handler is called when the Save Contact button is clicked. It’s a straightforward application of saving the contact, as described in Editing and Saving a Record, and then updating the user interface.