4

In the salesforce trailhead "Lightning Web Components and Salesforce Data: Use Apex to Work with Data" we have the following code:

import { LightningElement, wire } from "lwc";
import NAME_FIELD from "@salesforce/schema/Account.Name";
import REVENUE_FIELD from "@salesforce/schema/Account.AnnualRevenue";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
import getAccounts from "@salesforce/apex/AccountController.getAccounts";
const COLUMNS = [
  { label: "Account Name", fieldName: NAME_FIELD.fieldApiName, type: "text" },
  {
    label: "Annual Revenue",
    fieldName: REVENUE_FIELD.fieldApiName,
    type: "currency"
  },
  { label: "Industry", fieldName: INDUSTRY_FIELD.fieldApiName, type: "text" }
];
export default class AccountList extends LightningElement {
  columns = COLUMNS;
  @wire(getAccounts)
  accounts;
}

In this example, and in many others, field variables such as FIRST_NAME are imported via the "@salesforce/schema/ methodology. Later, they are referenced via code such as REVENUE_FIELD.fieldApiName.

Why is this? Is there a technical reason for it? Is it just a syntax standard? Given that the api name is already hardcoded via the import lines, why not just move that coding directly to where the API names are referenced? Something like this:

const COLUMNS = [
  { label: "Account Name", fieldName: 'Name', type: "text" },
  { label: "Annual Revenue", fieldName: "AnnualRevenue", type: "currency" },
  { label: "Industry", fieldName: "Industry", type: "text" }
];

1 Answer 1

7

As mentioned in the @salesforce/schmea docs, there's many benefits:

  1. Salesforce verifies that the objects and fields exist. It'll catch typos of the API name as well
  2. Prevents used objects/fields from being deleted
  3. The big benefit: Cascades any renamed objects and fields into your component's source code. This means if you change the API name of the field it'll automatically change in your LWC without you having to search and replace it if it was hard-coded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.