Work with a Single Record
What You’ll Do
Ursus park rangers need your help to track down bears that wander in the park. They already have some information entered in Salesforce, but they need you to provide them with a customized app experience.
Create the Bear Location Component
- In VS Code, right-click the
lwc
folder and click SFDX: Create Lightning Web Component. - Name the component
bearLocation
. - Edit the
bearLocation.js-meta.xml
file, and replace<isExposed>false</isExposed>
with these lines.<isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <objects> <object>Bear__c</object> </objects> </targetConfig> </targetConfigs>
This ensures that your component can be placed only on Bear record pages. - Replace the contents of
bearLocation.html
with the following markup.<template> <lightning-card title={cardTitle} icon-name="standard:address"> <lightning-map map-markers={mapMarkers} zoom-level="12"></lightning-map> </lightning-card> </template>
Code highlights:- We display a card component with a dynamic title based on the
cardTitle
expression. - The card contains a map component with markers defined by
mapMarkers
.
- We display a card component with a dynamic title based on the
- Replace the contents of
bearLocation.js
with the following.import { LightningElement, api, wire } from 'lwc'; import { getRecord, getFieldValue } from 'lightning/uiRecordApi'; // Set Bear object fields const NAME_FIELD = 'Bear__c.Name'; const LOCATION_LATITUDE_FIELD = 'Bear__c.Location__Latitude__s'; const LOCATION_LONGITUDE_FIELD = 'Bear__c.Location__Longitude__s'; const bearFields = [ NAME_FIELD, LOCATION_LATITUDE_FIELD, LOCATION_LONGITUDE_FIELD ]; export default class BearLocation extends LightningElement { @api recordId; name; mapMarkers = []; @wire(getRecord, { recordId: '$recordId', fields: bearFields }) loadBear({ error, data }) { if (error) { // TODO: handle error } else if (data) { // Get Bear data this.name = getFieldValue(data, NAME_FIELD); const Latitude = getFieldValue(data, LOCATION_LATITUDE_FIELD); const Longitude = getFieldValue(data, LOCATION_LONGITUDE_FIELD); // Transform bear data into map markers this.mapMarkers = [{ location: { Latitude, Longitude }, title: this.name, description: `Coords: ${Latitude}, ${Longitude}` }]; } } get cardTitle() { return (this.name) ? `${this.name}'s location` : 'Bear location'; } }
Code highlights:- We import a
getRecord
adapter that allow us to use the Lightning Data Service to retrieve records without having to write Apex. - We import a
getFieldValue
helper function to retrieve field values. - We assemble a list of hard-coded field names from the
Bear__c
object in thebearFields
constant. Note that this approach doesn’t support referential integrity. The existence of the object and fields cannot be checked at compile time. This means thatBear__c
or any of its fields could be deleted even though they are used in your code. We use another approach that supports referential integrity in our next component. - The
recordId
property decorated with@api
automatically receives the current record id. - We use an
@wire
decorator on theloadBear
function to fetch data and errors then pass them to the function.@wire
is configured to call thegetRecord
adapter function with some parameters. Those parameters are the record id and the list of record fields that we wish to retrieve. Thanks to the@wire
decorator,loadBear
is automatically called when the component loads or when the record id changes. - In this first version of our component we are not handling errors. We skip that for now.
- If there are no errors, we save the bear name and build a map marker with the bear’s coordinates.
- We import a
- Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.
Add the Bear Location Component to the Bear Record Page
Now that we have implemented our component, let’s add it to a page to view it.
- In your org, navigate to the Bears tab and open any record.
- Click Setup ( ) and select Edit Page.
- Under Custom Components, find your bearLocation component and drag it to the top of the right-hand column.
- Click Save.
- Since this is the first time we’ve modified the standard Bear record page, we need to activate the updated page so that our users can see what we’ve done. Click Activate.
- Click App Default tab.
- Click Assign as App Default.
- Check Ursus Park.
- Click Next, Next, and then Save.
- Click Back to return to the Bear record page and check your work.
Well done! We can now see the bear on a map. Let’s continue to customize the bear record page.
Create the Bear Supervisor Component
Park rangers are assigned to supervise specific bears. If a bear is spotted doing something reckless, park employees must be able to quickly reach out to the bear’s supervisor. You are going to help by adding a bear supervisor card on the bear record page.
- In VS Code, right-click the
lwc
folder and click SFDX: Create Lightning Web Component. - Name the component
bearSupervisor
. - Edit the
bearSupervisor.js-meta.xml
file, and replace<isExposed>false</isExposed>
with these lines.<isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <objects> <object>Bear__c</object> </objects> </targetConfig> </targetConfigs>
This enables your component to be placed on Bear record pages. - Replace the contents of
bearSupervisor.html
with:<template> <lightning-card title="Supervisor" icon-name="standard:people"> <div class="slds-var-m-around_medium"> <!-- Show supervisor when bear is loaded --> <template if:true={bear.data}> <lightning-record-form object-api-name="Contact" record-id={supervisorId} layout-type="Compact"> </lightning-record-form> </template> <!-- Data failed to load --> <template if:true={bear.error}> <div class="slds-text-color_error"> An error occurred while loading the bear record </div> </template> </div> </lightning-card> </template>
Code highlights:- We use an
if:true
directive to conditionally render the supervisor once the bear data is loaded. - We display a compact view of the supervisor (Contact) record with a
lightning-record-form
. - We use an
if:true
directive and theerror
property to conditionally render an error message if we can’t load the bear record.
- We use an
- Replace the contents of
bearSupervisor.js
with:import { LightningElement, api, wire } from 'lwc'; import { getRecord, getFieldValue } from 'lightning/uiRecordApi'; // Import Bear object fields import SUPERVISOR_FIELD from '@salesforce/schema/Bear__c.Supervisor__c'; const bearFields = [SUPERVISOR_FIELD]; export default class BearSupervisor extends LightningElement { @api recordId; // Bear Id @wire(getRecord, { recordId: '$recordId', fields: bearFields }) bear; get supervisorId() { return getFieldValue(this.bear.data, SUPERVISOR_FIELD); } }
Code highlights:- We import the
Bear__c.Supervisor__c
field via a schema import instead of using a hard-coded string like we did previously in the bear location component. The major benefit of this approach is that it ensures referential integrity. - We retrieve the bear record using the
@wire
decorator and thegetRecord
adapter. - We expose a
supervisorId
expression. The expression uses thegetFieldValue
function to retrieve the value of the supervisor field.
- We import the
- Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.
Add the Bear Supervisor Component to the Bear Record Page
Let’s add our new component to the bear record page.
- In your org, navigate to a bear record page by clicking the Bears tab and clicking on any bear. From the bear record page, click Setup ( ) and select Edit Page.
- Under Custom Components, find your bearSupervisor component and drag it under the bearLocation component.
- Click Save and Back to return to the record page and check your work.
That’s it for this step. We’ve seen how Lightning web components can handle single records with the @wire
adapter. Let’s now move on to lists of records.