Start tracking your progress
Trailhead Home
Trailhead Home

Get Started with Lightning Data Service for Aura Components

Learning Objectives

After completing this unit, you’ll be able to:

  • Describe what Lightning Data Service for Aura Components is.
  • Explain how Lightning Data Service can improve your components’ performance.
  • Use Lightning Data Service to load records into your UI.

What Is Lightning Data Service?

Note

Note

As of the Spring ’19 release (API version 45.0), you can build Lightning components using two programming models: the Lightning Web Components model and the original Aura Components model. Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning web components and Aura components can coexist and interoperate on a page. Lightning Data Service supports both, but this module covers Aura components only.

We built Lightning Data Service (LDS) to serve as the data layer for Lightning. LDS is the Lightning Components counterpart to the Visualforce standard controller, providing access to the data displayed on a page. Without LDS, each component within an app makes independent calls to the server to perform CRUD operations on a record, even if all components in the app pull from the same record data. Each server call reduces performance, leaving users twiddling their thumbs instead of working with their data. These independent server calls can also lead to inconsistencies, creating situations where a server call refreshes one component, leaving other components out of date.

Lightning Data Service identifies and eliminates requests that involve the same record data, sending a single shared data request that updates all relevant components. Not only does this eliminate inconsistent data between components, it also provides a way to cache data to work offline in case the user gets disconnected, intelligently syncing the data once the connection is restored.

Animation showing an application that uses Lightning Data Service to populate its components

This gif shows a property management application that uses Lightning Data Service to edit and update its components. The sale status progress bar automatically updates the property’s details when the status is updated.

Animation showing an application that uses Lightning Data Service to populate its components

This gif shows a second component within the same page that creates and displays appointments for the parent record.

In a nutshell, Lightning Data Service provides reusable Aura components that:
  • Minimize XMLHttpRequests (XHRs)
  • Fetch records once, reducing network transfers, app server load, and database server load
  • Cache record data on the client, separate from component metadata
  • Share record data across components
  • Enable progressive record loading, caching, and merging more fields and layouts into the cache
  • Enable proactive cache population
  • Promote consistency by using only one instance of the record data across multiple components
  • Create notifications when record data changes

If you have a Lightning application that creates, reads, updates, or deletes records, LDS is the best, most efficient way to do CRUD operations.

LDS is here to simplify your life. Adopting LDS means you no longer have to write your own controller code. All your data access code is contained within the LDS component, significantly reducing the complexity of your apps and pages. This reduced complexity means that you don’t have to spend as much time on performance and quality testing. Think of the cycles you can save!

Meet the Form-Based Components and force:recordData

So how do you access the benefits of Lightning Data Service? Simple! All you have to do is use one of the following form-based components , or the very versatile force:recordData component.

Form Function
Display, create, or edit records lightning:recordForm
Display records only lightning:recordViewForm (with lightning:outputField)
Create or edit records only lightning:recordEditForm (with lightning:inputField)
Display, create, edit, or delete records with granular customization force:recordData

For most use cases, lightning:recordForm provides a great starting point. It combines and simplifies the functionality of lightning:recordViewForm and lightning:recordEditForm. The lightning:recordForm component also switches from edit mode to view mode after changes are submitted successfully. You get automatic field mapping with field-level validation with the form-based components.

In this example, lightning:recordForm displays the account name field and label with a pencil icon, just like how it appears on a record detail page. When the pencil icon is clicked, the field becomes editable with the Cancel and Save buttons shown below it. The record ID is inherited from the record page via the force:hasRecordId interface. Leaving out the recordId attribute displays a form that creates a new record.

<!-- Add this component to an account record Lightning page -->
<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId">
    <aura:attribute name="recordId" type="String" />
    <lightning:card title="Display, Create, or Edit Records">
        <lightning:recordForm recordId="{!v.recordId}" 
                              objectApiName="Account"
                              fields="Name" />
    </lightning:card>
</aura:component>

For more advanced use cases that require custom field layouts using CSS and custom rendering of record data, use lightning:recordViewForm and lightning:recordEditForm.

In this example, lightning:recordEditForm displays an input field with the account name of the record being viewed. The custom Create new button handles the record update when clicked. lightning:recordViewForm displays a read-only account name field and label. lightning:messages displays any errors during record update.

<!-- Add this component to an account record Lightning page -->
<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId">
    <lightning:card title="Display, Create, or Edit Records">
        <lightning:recordEditForm recordId="{!v.recordId}"
                                  objectApiName="Account">
            <lightning:messages />
            <lightning:inputField fieldName="Name" />
            <lightning:button class="slds-m-top_small" type="submit" label="Create new" />
        </lightning:recordEditForm>

        <lightning:recordViewForm recordId="{!v.recordId}" objectApiName="Account">
            <lightning:messages />
            <lightning:outputField fieldName="Name" />
        </lightning:recordViewForm>
    </lightning:card>
</aura:component>
Note

Note

Explore the form-based components in the Build Flexible Apps with Lightning Components project. The rest of this module walks you through the force:recordData component.

The form-based components take care of layout, validation, CRUD changes, and error handling. With powerful form-based components like these, who needs force:recordData? On its own, force:recordData doesn’t include any UI elements; it’s simply logic and a way to communicate to the server. The lack of UI elements makes force:recordData a powerful addition. Use it to create highly customizable user interfaces beyond what the form-based components provide. You can use custom components to display the data fetched by force:recordData.

One of the simplest uses of LDS is loading records. To load a record on the client side, you have to add the force:recordData tag to your component, and set your recordId, mode, and layoutType or fields attributes.

  • recordId specifies the record to load. Records can’t be loaded without a recordId.
  • mode can be set to either EDIT or VIEW, which determines the behavior of notifications and what operations are available to perform with the record. If you’re using force:recordData to change the record in any way, set the mode to EDIT.
  • layoutType specifies the layout (FULL or COMPACT) used to display the record, which determines what fields are included. Using layoutType allows your component to adapt to layout definitions.
  • fields specifies which fields in the record to query.

The fields or layoutType attribute must be provided to load a record’s field data. Since admins usually modify layouts, using fields is a more flexible way to get the fields you need.

The force:recordData tag also supports a set of target* attributes, which are attributes that force:recordData populates itself. The target* attributes can be used to allow access from the UI.

  • targetRecord is populated with the loaded record
  • targetFields is populated with the simplified view of the loaded record
  • targetError is populated with any errors
<force:recordData aura:id="forceRecordCmp" 
  <!-- aura:id is required to reference the component in your Javascript controller -->
    recordId="{!v.recordId}"
    layoutType="{!v.layout}"
    fields="{!v.fieldsToQuery}"
    mode="VIEW"
    targetRecord="{!v.record}"
    targetFields="{!v.simpleRecord}" 
    targetError="{!v.error}"
/>

In this example, lightning:formattedtext displays the Name field from the record loaded by force:recordData.

<aura:component>

    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="record" type="Object" />
    <aura:attribute name="simpleRecord" type="Object" />

     <force:recordData recordId="{!v.recordId}"
          targetRecord ="{!v.record}"
          targetFields ="{!v.simpleRecord}"
          fields="Id, Name" />

    <div class="recordName">
        <p class="slds-text-heading--medium">
            <lightning:formattedtext title="Record Name" value="{!v.simpleRecord.Name}" /></p>
    </div>

</aura:component>

Several Aura methods to modify records are available. Here’s a quick overview of the methods you can use in your JavaScript component controllers.

  • saveRecord() inserts or updates the record loaded into the force:recordData component.
  • deleteRecord() deletes the loaded record.
  • getNewRecord() loads a new record template that performs an insert when saved.
  • reloadRecord() reruns the loading code to overwrite the current targetRecord with the current attribute values.

We go into how to use force:recordData in greater detail in the next unit.