Skip to main content

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

  1. In VS Code, right-click the lwc folder and click SFDX: Create Lightning Web Component.
  2. Name the component bearLocation.
  3. 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.
  4. Replace the contents of bearLocation.htmlwith 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.
  5. Replace the contents of bearLocation.jswith 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 the bearFields 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 that Bear__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 the loadBear function to fetch data and errors then pass them to the function. @wire is configured to call the getRecord 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.
  6. 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.

  1. In your org, navigate to the Bears tab and open any record.
  2. Click Setup ( Setup Gear ) and select Edit Page.
  3. Under Custom Components, find your bearLocation component and drag it to the top of the right-hand column.
  4. Click Save.
  5. 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.
  6. Click App Default tab.
  7. Click Assign as App Default.
  8. Check Ursus Park.
  9. Click Next, Next, and then Save.
  10. Click Back to return to the Bear record page and check your work.

Bear location component on the bear record page

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.

  1. In VS Code, right-click the lwc folder and click SFDX: Create Lightning Web Component.
  2. Name the component bearSupervisor.
  3. 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.
  4. Replace the contents of bearSupervisor.htmlwith:
    <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 the error property to conditionally render an error message if we can’t load the bear record.
  5. Replace the contents of bearSupervisor.jswith:
    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 the getRecord adapter.
    • We expose a supervisorId expression. The expression uses the getFieldValue function to retrieve the value of the supervisor field.
  6. 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.

  1. 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 ( Setup Gear) and select Edit Page.
  2. Under Custom Components, find your bearSupervisor component and drag it under the bearLocation component.
  3. Click Save and Back to return to the record page and check your work.

Bear supervisor component on the bear record page

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.

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities