Developing a Robust Salesforce Testing Strategy Developing a Robust Salesforce Testing Strategy Salesforce testing is an important requirement to keep the performance of applications as expected. However, they need to undergo a robust testing strategy …
lightning-record-view-form A lightning-record-view-form component is a wrapper component that accepts a record ID and is used to display one or more fields and labels associated with that record using lightning-output-field. lightning-record-view-form requires a record ID …
Difference between Export & Export All in data loader is really interesting. I was asked this question in one of my job interview. There are two buttons available in dataloader ‘Export’ & ‘Export All’. Difference …
Lookup Screen Component in Salesforce Lightning Flow Lookup Screen Component in Salesforce Lightning Flow: Salesforce has released a new screen component – Lookup. As the name suggests, this new screen component lets users search for …
Use Lightning Components in Visualforce Pages Use Lightning Components in Visualforce Pages How To Display Lightning Component In Visualforce Page In this post, we will see how we can use Lightning Components in Visualforce Pages …
A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members. In this post we will see how we can use wrapper class in lightning component to display data in lightning component. For details about how we can use wrapper class in visualforce page check wrapper class in Apex. If you are looking for wrapper class in Lightning Aura component, please refer to wrapper class in lightning component salesforce.
Wrapper Class in LWC Example
Let’s see an example of wrapper class in LWClightning component salesforce. In this example, we will create AcoountContactWrapper and will display account and contact details and display on lightning web component.
Apex class controller with the wrapper class
AccountContactController.cls
public class AccountContactController{
@AuraEnabled(cacheable=true)
public static List<AccountContactListWrapper> getAllAccountWithContacts(){
List<AccountContactListWrapper> accWrapperList = new List<AccountContactListWrapper>();
List<Account> accList = [SELECT Id, Name, BillingState, Website, Phone,
(SELECT Id, FirstName, LastName, Name, Email From Contacts)
FROM Account WHERE Name LIMIT 5];
if(!accList.isEmpty()){
for(Account acc : accList){
AccountContactListWrapper accWrapper = new AccountContactListWrapper();
accWrapper.accRecord = acc;
accWrapper.contactList = acc.Contacts;
accWrapper.contactCount = acc.Contacts.size();
accWrapperList.add(accWrapper);
}
}
return accWrapperList;
}
// wrapper class with @AuraEnabled and {get;set;} properties
public class AccountContactListWrapper{
@AuraEnabled
public Account accRecord{get;set;}
@AuraEnabled
public List<Contact> contactList{get;set;}
@AuraEnabled
public Integer contactCount{get;set;}
}
}
wrapperClassExampleLWC.html
<template>
<lightning-card title="Account with Contacts using wrapper class in LWC" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<template if:true={accountsWithContacts}>
<template for:each={accountsWithContacts} for:item="accWithContacts">
<div key={accWithContacts.accRecord.Id}>
<div class="slds-text-heading_medium">{accWithContacts.accRecord.Name}</div>
<template if:true={accWithContacts.contactList}>
Contacts Count is {accWithContacts.contactCount}. Here is list:
<ul class="slds-list_dotted">
<template for:each={accWithContacts.contactList} for:item="con">
<li key={con.Id}>{con.Name}</li>
</template>
</ul>
</template>
</div>
</template>
</template>
<template if:true={error}>
{error}
</template>
</div>
</lightning-card>
</template>
wrapperClassExampleLWC.js
import { LightningElement, wire, track } from 'lwc';
import getAllAccountWithContactsList from '@salesforce/apex/AccountContactController.getAllAccountWithContacts';
export default class WrapperClassExampleLWC extends LightningElement {
@track accountsWithContacts;
@track error;
@wire(getAllAccountWithContactsList)
wiredAccountsWithContacts({ error, data }) {
if (data) {
this.accountsWithContacts = data;
} else if (error) {
console.log(error);
this.error = error;
}
}
}
Navigation Service in LWC(Lightning Web Components)
Navigation Service in LWC(Lightning Web Components)
To navigate in Lightning Experience, Lightning Communities, and the Salesforce app, use the navigation service, lightning/navigation.
The lightning/navigation service is supported only in Lightning Experience, Lightning Communities, and the Salesforce app. It isn’t supported in other containers, such as Lightning Components for Visualforce, or Lightning Out. This is true even if you access these containers inside Lightning Experience or the Salesforce app. We can use navigation services in LWC to Navigate to Pages, Records, and Lists.
There are different types of navigation options available. Let’s discuss the basic one
Basic Navigation
Use the navigation service, lightning/navigation, to navigate to many different page types, like records, list views, and objects. Also use the navigation service to open files.
Instead of a URL, the navigation service uses a PageReference. A PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page. Using a PageReference insulates your component from future changes to URL formats. It also allows your component to be used in multiple applications, each of which can use different URL formats.
Navigation service uses a PageReference. PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page.
Page type(String) and attributes(Object) are required parameters, state(Object) is optional parameter.
Use Navigation Service in LWC
Here are steps to use the navigation service
First, we need to import the lightning/navigation module.
import { NavigationMixin } from 'lightning/navigation';
Apply the NavigationMixin function to your component’s base class.
export default class MyCustomElement extends NavigationMixin(LightningElement) {}
Create a plain JavaScript PageReference object that defines the page
To dispatch the navigation request, call the navigation service’s [NavigationMixin.Navigate](pageReference, [replace])
The NavigationMixin adds two APIs to your component’s class. Since these APIs are methods on the class, they must be invoked with this reference.
[NavigationMixin.Navigate](pageReference, [replace]): A component calls this[NavigationMixin.Navigate] to navigate to another page in the application.
[NavigationMixin.GenerateUrl](pageReference): A component calls this[NavigationMixin.GenerateUrl] to get a promise that resolves to the resulting URL. The component can use the URL in the href attribute of an anchor. It can also use the URL to open a new window using the window.open(url) browser API.
Navigation Service in LWC Example
navigationExampleLWC.html
<template>
<lightning-card title="Navigation Service in LWC(Lightning Web Components)">
<lightning-card title="Navigate To Record Example">
<lightning-button label="New Account" onclick={navigateToNewAccountPage}></lightning-button>
<lightning-button label="View Account" onclick={navigateToViewAccountPage}></lightning-button>
<lightning-button label="Edit Account" onclick={navigateToEditAccountPage}></lightning-button>
</lightning-card>
<lightning-card title="Navigate To Views">
<lightning-button label="Account Recent list View" onclick={navigateToAccountListView}></lightning-button>
<lightning-button label="Account Related List" onclick={navigateToContactRelatedList}></lightning-button>
</lightning-card>
<lightning-card title="Navigate To Home">
<lightning-button label="Navigate to Home" onclick={navigateToHomePage}></lightning-button>
<lightning-button label="Navigate to Contact Home " class="slds-m-around_medium" onclick={navigateToContactHome}></lightning-button>
</lightning-card>
<lightning-card title="Navigate To Other">
<lightning-button label="Navigate to Chatter Home" onclick={navigateToChatter}></lightning-button>
<lightning-button label="Navigate to Reports" onclick={navigateToReports}></lightning-button>
<lightning-button label="Navigate to Tab" onclick={navigateToTab}></lightning-button>
<lightning-button label="Navigate to SFDCPoint" onclick={navigateToWebPage}></lightning-button>
<lightning-button label="Navigate to Files " class="slds-m-around_medium" onclick={navigateToFilesHome}></lightning-button>
</lightning-card>
<lightning-card title="Navigate To Component">
<lightning-button label="Navigate to Visualforce page " onclick={navigateToVFPage}></lightning-button>
<lightning-button label="Navigate to Aura Lightning Component " class="slds-m-around_medium" onclick={navigateToLightningComponent}></lightning-button>
</lightning-card>
</lightning-card>
</template>
navigationExampleLWC.js
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class NavigationExampleLWC extends NavigationMixin(LightningElement) {
@api recordId;
// Navigate to New Account Page
navigateToNewAccountPage() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'new'
},
});
}
// Navigate to View Account Page
navigateToViewAccountPage() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
},
});
}
// Navigate to Edit Account Page
navigateToEditAccountPage() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'edit'
},
});
}
// Navigation to Account List view(recent)
navigateToAccountListView() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'list'
},
state: {
filterName: 'Recent'
},
});
}
// Navigation to Contact related list of account
navigateToContactRelatedList() {
this[NavigationMixin.Navigate]({
type: 'standard__recordRelationshipPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
relationshipApiName: 'Contacts',
actionName: 'view'
},
});
}
//Navigate to home page
navigateToHomePage() {
this[NavigationMixin.Navigate]({
type: 'standard__namedPage',
attributes: {
pageName: 'home'
},
});
}
// Navigation to contant object home page
navigateToContactHome() {
this[NavigationMixin.Navigate]({
"type": "standard__objectPage",
"attributes": {
"objectApiName": "Contact",
"actionName": "home"
}
});
}
//Navigate to chatter
navigateToChatter() {
this[NavigationMixin.Navigate]({
type: 'standard__namedPage',
attributes: {
pageName: 'chatter'
},
});
}
//Navigate to Reports
navigateToReports() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Report',
actionName: 'home'
},
});
}
//Navigate to Files home
navigateToFilesHome() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'ContentDocument',
actionName: 'home'
},
});
}
// Navigation to lightning component
navigateToLightningComponent() {
this[NavigationMixin.Navigate]({
"type": "standard__component",
"attributes": {
//Here customLabelExampleAura is name of lightning aura component
//This aura component should implement lightning:isUrlAddressable
"componentName": "c__customLabelExampleAura"
}
});
}
// Navigation to web page
navigateToWebPage() {
this[NavigationMixin.Navigate]({
"type": "standard__webPage",
"attributes": {
"url": "https://www.sfdcpoint.com/"
}
});
}
//Navigate to visualforce page
navigateToVFPage() {
this[NavigationMixin.GenerateUrl]({
type: 'standard__webPage',
attributes: {
url: '/apex/AccountVFExample?id=' + this.recordId
}
}).then(generatedUrl => {
window.open(generatedUrl);
});
}
// Navigation to Custom Tab
navigateToTab() {
this[NavigationMixin.Navigate]({
type: 'standard__navItemPage',
attributes: {
//Name of any CustomTab. Visualforce tabs, web tabs, Lightning Pages, and Lightning Component tabs
apiName: 'CustomTabName'
},
});
}
}
for:each template directives in LWC(Lightning Web Component)
To render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat. We can call it for loop in LWC.
The iterator directive has first and last properties that let you apply special behaviors to the first and last items in an array.
Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time.
for:each LWC(Lightning Web Component)
When using the for:each directive, use for:item=”currentItem” to access the current item. This example doesn’t use it, but to access the current item’s index, use for:index=”index”.
To assign a key to the first element in the nested template, use the key={uniqueId} directive.
for:each LWC example
AccountHelper.cls
public with sharing class AccountHelper {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name, Type, Rating,
Phone, Website, AnnualRevenue
FROM Account];
}
}
Under Custom Components, find your accountListForEachLWC component and drag it on right hand side top.
Click Save and activate.
We will have the following output:
iterator in LWC(Lightning Web Component)
To apply special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
Use iteratorName to access these properties:
value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.
index—The index of the item in the list.
first—A boolean value indicating whether this item is the first item in the list.
last—A boolean value indicating whether this item is the last item in the list.
Future Methods in Salesforce using @future annotation
A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also use future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
Future method syntax
global class FutureClass {
@future
public static void myFutureMethod() {
// Perform some operations
}
}
Use @future annotation before the method declaration.
Future methods must be static methods, and can only return a void type.
The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
Future methods can’t take standard or custom objects as arguments.
A common pattern is to pass the method a list of record IDs that you want to process asynchronously.
global class FutureMethodRecordProcessing {
@future
public static void processRecords(List<ID> recordIds){
// Get those records based on the IDs
List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds];
// Process records
}
}
Future method callouts using @future(callout=true)
To allow callout from the future method annotation needs an extra parameter (callout=true) to indicate that callouts are allowed. Here is example
global class FutureMethodExample {
@future(callout=true)
public static void getStockQuotes(String acctName){
// Perform a callout to an external service
}
}
Test Class for Future Methods
To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
@isTest
private class MixedDMLFutureTest {
@isTest static void test1() {
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
// System.runAs() allows mixed DML operations in test context
System.runAs(thisUser) {
// startTest/stopTest block to run future method synchronously
Test.startTest();
MixedDMLFuture.useFutureMethod();
Test.stopTest();
}
// The future method will run after Test.stopTest();
// Verify account is inserted
Account[] accts = [SELECT Id from Account WHERE Name='Acme'];
System.assertEquals(1, accts.size());
// Verify user is inserted
User[] users = [SELECT Id from User where username='mruiz@awcomputing.com'];
System.assertEquals(1, users.size());
}
}
Future Method Performance Best Practices
Salesforce uses a queue-based framework to handle asynchronous processes from such sources as future methods and batch Apex. This queue is used to balance request workload across organizations. Use the following best practices to ensure your organization is efficiently using the queue for your asynchronous processes.
Avoid adding large numbers of future methods to the asynchronous queue, if possible. If more than 2,000 unprocessed requests from a single organization are in the queue, any additional requests from the same organization will be delayed while the queue handles requests from other organizations.
Ensure that future methods execute as fast as possible. To ensure fast execution of batch jobs, minimize Web service callout times and tune queries used in your future methods. The longer the future method executes, the more likely other queued requests are delayed when there are a large number of requests in the queue.
Test your future methods at scale. Where possible, test using an environment that generates the maximum number of future methods you’d expect to handle. This helps determine if delays will occur.
Consider using batch Apex instead of future methods to process large numbers of records.
Introducing Playground – Share and Collaborate Salesforce Solutions
Are you a Salesforce developer or an administrator working on a development task?
Did you just spend writing a block of code again that you wrote a while ago?
Can’t recall where you last saw a similar solution that you’re implementing?
Have you hit a blocker while writing your code in apex or lightning?
Your best bet – google it! But can you always find what you’re looking for? Say even if you do, is it time consuming for you to clean it up and bring back to use?
If all you could think of was a YES, then look no further and get ready to play!
Welcome tothePlayground– an intuitive, collaborative and easy-to-use cloud application to upload and share solutions within the Salesforce ecosystem.
Playground is truly remarkable in making it super easy for developers to store their reusable code, to share it to the wider community and from having visitors search for an available solution to even letting them directly use it within their salesforce org with just a single click, oh yeah…that’s right – just one simple click. Now that’s called a power play!
We have an ever-increasing list of 49 amazing plays, fab five-some contributors and nearly 170 users with us already. Looking at the spectacular response, we are hopeful to be supporting the salesforce ecosystem even more.
Playground is built with an aim to “Reuse & Collaborate More”. With that in mind, here are top highlights of this app:
Designed specifically for Salesforce
Effective storage & organization of reusable assets at one place
Powerful search to find the right solution at the right time
Hassle free one-click deployments, straight into any Salesforce org
Insights to track the progress of any solution
Tracker to know how well a solution is accepted by the community
As echoed above, we wanted to build a one stop shop for all our fellow Salesforce users out there to store any reusable components and collaborate for a progressive future together.
Finally, it’s time to hit the playground and have some fun!
template if:true Conditional Rendering LWC(Lightning Web Component)
To render HTML conditionally, add the if:true|false directive to a nested <template> tag that encloses the conditional content. template if:true|falsedirective is used to display conditional data.
Render DOM Elements Conditionally Lightning Web Component
The if:true|false={property} directive binds data to the template and removes and inserts DOM elements based on whether the data is a truthy or falsy value.
template if:true LWC Example
Let’s see a simple example to show content based on the selection of checkbox. Example contains a checkbox labeled Show details. When a user selects or deselects the checkbox., based on that content is visible. This example has been copied from official link.
templateIFTrueExampleLWC.html
<template>
<lightning-card title="TemplateIFTrueConditionalRendering" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input type="checkbox" label="Show details" onchange={handleChange}></lightning-input>
<template if:true={areDetailsVisible}>
<div class="slds-m-vertical_medium">
These are the details!
</div>
</template>
</div>
</lightning-card>
</template>
Under Custom Components, find your templateIFTrueExampleLWC component and drag it on right hand side top.
Click Save and activate.
We will get the following Output
When user select the checkbox, we will see the following output
Let’s see some practical example. In this example, account list is fetched from the database. If there is some error in fetching account list then show error otherwise show account list
AccountHelper.cls
public with sharing class AccountHelper {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name, Type, Rating,
Phone, Website, AnnualRevenue
FROM Account];
}
}
lightning:recordForm Example lightning aura component
lightning:recordForm component allows you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning:recordEditForm or lightning:recordViewForm. The lightning:recordForm component provides these helpful features:
Switches between view and edit modes automatically when the user begins editing a field in a view form
Provides default Cancel and Save buttons in edit forms
Uses the object’s default record layout with support for multiple columns
Loads all fields in the object’s compact or full layout, or only the fields you specify
lightning:recordForm is less customizable. To customize the form layout or provide custom rendering of record data, use lightning:recordEditForm (add or update a record) and lightning:recordViewForm (view a record).
The objectApiName attribute is always required, and the recordId is required only when you’re editing or viewing a record.
lightning:recordForm implements Lightning Data Service and doesn’t require additional Apex controllers to create or edit record data. It also takes care of field-level security and sharing for you, so users see only the data that they have access to.
Modes
The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:
edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the record-id. Edit mode is the default when record-id is not provided, and displays a form to create new records.
view – Creates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default when recordId is provided.
readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.
Specifying Record Fields
For all modes, the component expects the fields attribute or the layoutType attribute.
Use the fields attribute to pass record fields as an array of strings. The fields display in the order you list them.
Use the layoutType attribute to specify a Full or Compact layout. Layouts are typically defined (created and modified) by administrators. Specifying record data using layout-type loads the fields in the layout definition. All fields that have been assigned to the layout are loaded into the form.
To see the fields in the layout types in your org:
Full – The full layout corresponds to the fields on the record detail page. From the management settings for the object that you want to edit, go to Page Layouts.
Compact – The compact layout corresponds to the fields on the highlights panel at the top of the record. From the management settings for the object that you want to edit, go to Compact Layouts.
lightning-record-form LWC (Lightning Web Component)
lightning-record-form LWC
lightning-record-form component allows you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning-record-edit-form or lightning-record-view-form. The lightning-record-form component provides these helpful features:
Switches between view and edit modes automatically when the user begins editing a field in a view form
Provides Cancel and Save buttons automatically in edit forms
Uses the object’s default record layout with support for multiple columns
Loads all fields in the object’s compact or full layout, or only the fields you specify
lightning-record-form is less customizable. To customize the form layout or provide custom rendering of record data, use lightning-record-edit-form (add or update a record) and lightning-record-view-form (view a record).
The object-api-name attribute is always required, and the record-id is required only when you’re editing or viewing a record.
lightning-record-form implements Lightning Data Service and doesn’t require additional Apex controllers to create or edit record data. It also takes care of field-level security and sharing for you, so users see only the data that they have access to.
Modes
The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:
edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the record-id. Edit mode is the default when record-id is not provided, and displays a form to create new records.
view – Creates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default when record-id is provided.
readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.
Specifying Record Fields
For all modes, the component expects the fields attribute or the layout-type attribute.
Use the fields attribute to pass record fields as an array of strings. The fields display in the order you list them.
Use the layout-type attribute to specify a Full or Compact layout. Layouts are typically defined (created and modified) by administrators. Specifying record data using layout-type loads the fields in the layout definition. All fields that have been assigned to the layout are loaded into the form.
To see the fields in the layout types in your org:
Full – The full layout corresponds to the fields on the record detail page. From the management settings for the object that you want to edit, go to Page Layouts.
Compact – The compact layout corresponds to the fields on the highlights panel at the top of the record. From the management settings for the object that you want to edit, go to Compact Layouts.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class LightningRecordFormCreateExampleLWC extends LightningElement {
// objectApiName is "Account" when this component is placed on an account record page
@api objectApiName;
fields = [NAME_FIELD, REVENUE_FIELD, INDUSTRY_FIELD];
handleSuccess(event) {
const evt = new ShowToastEvent({
title: "Account created",
message: "Record ID: " + event.detail.id,
variant: "success"
});
this.dispatchEvent(evt);
}
}
lightning-record-edit-form LWC (Lightning Web Component)
A lightning-record-edit-form component is a wrapper component that accepts a record ID and object name. It is used to add a Salesforce record or update fields in an existing record. The component displays fields with their labels and the current values and enables you to edit their values. The lightning-input-field component is used inside the lightning-record-edit-form to create editable fields. The lightning-output-field component and other display components such as lightning-formatted-name can be used to display read-only information in your form. lightning-record-edit-form implements Lightning Data Service. It doesn’t require additional Apex controllers to create or update records. Using lightning-record-edit-form to create or update records with Apex controllers can lead to unexpected behaviors. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.
lightning-record-edit-form supports the following features:
Editing a record’s specified fields, given the record ID.
Creating a record using specified fields.
Customizing the form layout
Custom rendering of record data
Editing a Record
To enable record editing, pass in the ID of the record and the corresponding object API name to be edited. Specify the fields you want to include in the record edit layout using lightning-input-field.
Include a lightning-button component with type=”submit” to automatically save any changes in the input fields when the button is clicked.
Let’s create an example to edit account record using lightning-record-edit-form in Lightning Web Component
Now we can add this LWC component on the Contact Record page.
Go to Contact record
Click Setup (Gear Icon) and select Edit Page.
Under Custom Components, find your recordEditFormEditExampleLWC component and drag it on Contact Page.
Click Save and activate.
We will get the following output
Creating a Record
To enable record creation, pass in the object API name for the record to be created. Specify the fields you want to include in the record create layout using lightning-input-field components. For more information, see the lightning-input-field documentation.
Include a lightning-button component with type=”submit” to automatically save the record when the button is clicked.
Let’s create an example to create account record using lightning-record-edit-form in Lightning Web Component
Now we can add this LWC component on the Contact Record page.
Go to Contact record.
Click Setup (Gear Icon) and select Edit Page.
Under Custom Components, find your recordEditFormCreateExampleLWC component and drag it on Contact Page.
Click Save and activate.
We will get the following output
Displaying Forms Based on a Record Type
If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used.
Supported Objects
This component doesn’t support all Salesforce standard objects. For example, the Event and Task objects are not supported. This limitation also applies to a record that references a field that belongs to an unsupported object.
External objects and person accounts are not supported.
To work with the User object, specify FirstName and LastName instead of the Name compound field for the field-name values of lightning-input-field.
Error Handling
lightning-record-edit-form handles field-level validation errors and Lightning Data Service errors automatically. For example, entering an invalid email format for the Email field results in an error message when you move focus away from the field. Similarly, a required field like the Last Name field displays an error message when you leave the field blank and move focus away.
We need to include lightning-messages to support error handling and displaying of error messages. If the record edit layout includes a lightning-button component with type="submit", when the button is clicked the lightning-record-edit-form component automatically performs error handling and saves any changes in the input fields. Similarly, if the record create layout provides a submit button, when the button is clicked error handling is automatically performed and a new record is created with the input data you provide.
Lightning Spinner in LWC (Lightning Web Component)
What is Lightning Spinner in LWC?
Lightning Spinners are CSS loading indicators that should be shown when retrieving data or performing slow computations. lightning-spinner displays an animated spinner image to indicate that a request is loading. This component can be used when retrieving data or performing an operation that takes time to complete. In some cases, the first time a parent component loads, a stencil is preferred to indicate network activity.
lightning-spinner LWC example
Let’s first see a very simple example to show or hide lightning spinner using a toggle button
import { LightningElement, api } from 'lwc';
export default class LightningSpinnerLWCSimpleExample extends LightningElement {
@api isLoaded = false;
// change isLoaded to the opposite of its current value
handleClick() {
this.isLoaded = !this.isLoaded;
}
}
Now we can add this LWC component on the home page.
Go to Home page
Click Setup (Gear Icon) and select Edit Page.
Under Custom Components, find your lightningSpinnerLWCSimpleExample component and drag it on right-hand side top.
Click Save and activate.
We will see the following output. If the user will click on the toggle button then the spinner will toggle on or off.
lightning-spinner example with Apex
Let’s see one more real-life example where the user will click on the button to load account and during apex request lightning spinner loading image
AccountHelper class
public with sharing class AccountHelper {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name, Type, Rating,
Phone, Website, AnnualRevenue
FROM Account];
}
}
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. AcceptRead More
Privacy & Cookies Policy
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
Recent Comments