The main concept included in this recipe are:
Contact
record and then access the fields in an explicit manner.
<aside>
📂 Find this LWC in this folder: force-app\\main\\default\\lwc\\apexStaticSchema
</aside>
Inside the ContactController
class, the method getSingleContact
is exposed using the @AuraEnabled(cacheable=true)
decorator, this is required to be able to call this method from LWC.
This method returns 1 Contact
record:
@AuraEnabled(cacheable=true)
public static Contact getSingleContact() {
return [
SELECT Id, Name, Title, Phone, Email, Picture__c
FROM Contact
WITH SECURITY_ENFORCED
LIMIT 1
];
}
In order to use this method in the LWC, an import
is required.
Also, for every field to be used, there is an statically import like import NAME_FIELD from '@salesforce/schema/Contact.Name';
.
<aside> 💡 Doing so, Salesforce verifies that the objects and fields exist and prevents objects and fields from being deleted and cascades any renamed objects and fields into your component's source code. It also ensures that dependent objects and fields are included in change sets and packages. Importing references to objects and fields ensures that your code works, even when object and field names change.
</aside>
Following, the imported method is wired to the contact
property.
In the template, the name
, title
, and email
properties have getters that make usage of the getSObjectValue()
function to extract the value from the specified field. The getSObjectValue()
function has this signature: getSObjectValue(sobject, fieldApiName);
.
import { LightningElement, wire } from 'lwc';
import { getSObjectValue } from '@salesforce/apex';
**import getSingleContact from '@salesforce/apex/ContactController.getSingleContact';**
**import NAME_FIELD from '@salesforce/schema/Contact.Name';
import TITLE_FIELD from '@salesforce/schema/Contact.Title';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';**
export default class ApexStaticSchema extends LightningElement {
@wire(getSingleContact) contact;
get name() {
return this.contact.data
? getSObjectValue(this.contact.data, NAME_FIELD)
: '';
}