In this post, we will see how to add or show a Lightning web component in salesforce quick actions. When salesforce introduced LWC first time, LWC in quick action was not available, that time we encapsulated LWC component on Aura component and achieved this. But as part of the Salesforce summer release, they introduced this feature.
Add LWC in Quick Action
Define Component Metadata in the Configuration .xml File
In targets, add lightning__RecordAction as a target to designate the Lightning web component as a quick action on a record page.
Add a targetConfig and set targets to lightning__RecordAction.
import { LightningElement, api, wire } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
export default class LwcQuickAction extends LightningElement {
@api recordId;
@api objectApiName;
handleCancel(event) {
// Add your cancel button implementation here
this.dispatchEvent(new CloseActionScreenEvent());
}
}
lwcQuickAction.html
<template>
<lightning-quick-action-panel header="Test LWC Quick Action">
<p>This is Test LWC component in quick action</p>
<div slot="footer">
<lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
</div>
</lightning-quick-action-panel>
</template>
If we want to display a standard header and footer then we can use "lightning-quick-action-panel" tag.
For closing the quick action on a custom button click, we need to import "CloseActionScreenEvent" from 'lightning/actions' and dispatch that in an event.
In many use cases, we need to check recordtype conditions in apex logic. Below is the same peace of code that gives recordtypeId of given sobject name and recordType label.
String egRecordTypeID = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Record Type Label').getRecordTypeId();
Here we need to provide Sobject name in place of "Case" and recordType label in place of "Record Type Label"
The disconnectedCallback() is one of the life cycle functions of modern web components.
When disconnectedCallback() fired?
It gets invoked automatically when the corresponding web component gets removed from DOM. If we need to perform any logic when the component is removed from DOM, that logic can be added in disconnectedCallback(). This hook flows from Parent component to child. We use disconnectedCallback() to purging caches or removing event listeners that are created on connectedCallback().
In this example, we have two components. Those are 'disconnectedCallbackParentLwc' and 'disconnectedCallbackChildLwc'. Here disconnectedCallbackChildLwc referred in parent component. In the parent component, we have a button 'Show/Hide' to show and hiding the child component. Initially, the child component displayed, once users click on the button 'disconnectedCallbackChildLwc' the child component removed from DOM. Since the component getting removed from DOM, disconnectedCallback function on the child component gets invoked and an alert will appear.
disConnectedCallbackChildLwc.js
import { LightningElement } from 'lwc';
export default class DisConnectedCallbackChildLwc extends LightningElement {
disconnectedCallback() {
console.log('child disconnected callback')
}
}
disConnectedCallbackChildLwc.html
<template>
<p>I am child LWC component</p>
</template>
disConnectedCallbackParentLwc.js
import { LightningElement } from 'lwc';
export default class DisConnectedCallbackParentLwc extends LightningElement {
show = true;
handleShowHide() {
this.show = !this.show;
}
}
How to display Toast messages in Lightning Web Components
A lightning web component can send a toast notification that can be inform users of a success, error, or warning information. If we want to show a toast message notification in Lightning Experience or Lightning communities, then we need to import ShowToastEvent function from the lightning/platformShowToastEvent module. So that we can create ShowToastEvent in the function wherever we want. ShowToastEvent contains title, message, messageData, variant, mode parameters.
title: It is String attribute. Used for showing title of the toast and displayed as a heading.
message: It is a String attribute. It is used for showing message in the toast.
variant: It is a String attribute. It controls theme and icon displayed in the toast notification. We can give Success, Info, Error Warning values based on requirement.
mode: It is a string to define how toast notification should persistent. Valid values: sticky, pester, dismissable .
sticky: If we use this, toast notification will not be closed automatically, user need to click on close button to close toast notification.
dismissable: it's a default value. If we use this, user can see close button & toast notification closed automatically after 3 seconds.
pester: If we use this option, toast notification closed automatically after 3 seconds & user can't see close button.
Example: Show Toast messages in Lightning Web Components(LWC)
In below example we have four buttons, I.e Success, Info, Warning, Error. When particular button click event happens, we are dispatching ShowToastEvent event in the corresponding functions.
lwcShowToast.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LwcShowToast extends LightningElement {
//Sample Success Toast message code
showSuccessNotification() {
const evt = new ShowToastEvent({
title: "Success",
message: "This is sample success message",
variant: "success",
});
this.dispatchEvent(evt);
}
//Sample code for showing error message in Toast
showErrorNotification() {
const evt = new ShowToastEvent({
title: "Error",
message: "This is sample error message",
variant: "error",
});
this.dispatchEvent(evt);
}
//Sample code for showing warning message in Toast
showWarningNotification() {
const evt = new ShowToastEvent({
title: "Warning",
message: "This is sample warning message",
variant: "warning",
mode: "sticky"
});
this.dispatchEvent(evt);
}
//Sample code for showing Info message in Toast
showInfoNotification() {
const evt = new ShowToastEvent({
title: "Info",
message: "This is sample info message",
variant: "info",
mode: "pester"
});
this.dispatchEvent(evt);
}
}
In many scenarios we need to have current record id in the lightning web component. Id we want get current record id then we need to define "recordId" prublic property in corresponding lwc component JavaScript file and the lightning web component should be added into lightning record page.
How To Fetch Current Record Id In Lightning Web component Example
lwcGetRecordId.js
import { LightningElement, api } from 'lwc';
export default class LwcGetRecordId extends LightningElement {
@api recordId;
}
lwcGetRecordId.html
<template>
Current Record Id : {recordId}
</template>
Output:
Add above ligtning web component to any of the record page(Ex: Account, contact, opportunity....)
3. Fire an Event: Fire an Event when some event occurs on child component(Eg: Button onclick, onchange of Input
Text...).
Example:
var compEvent = component.getEvent("sampleComponentEvent");
compEvent.setParams({"message" : "Static Text" });
compEvent.fire();
4. We need to handle event on Parent Component. Handler name and registerEvent name should be same. We can
invoke function with the help of "action" attribute.
When the child function gets fired, it calls custom event and pass required parameter’s. After that event
invokes Handler method on Parent component(Eg: handleComponentEvent). By using "
event.getParam("eventAttributeName"); " we can retrieve values that are passed to custom event.
Example: Fire Parent Lightning Aura Component function from Child component and pass
parameters.
How to get Custom Label value in LWC (Lightning Web Components):
Usage of Custom Label: We know that we use custom label for error messages, constants and storing values which are translated into specific language by using translation workbench.
How to access Custom Label in LWC components
For accessing custom label value we need to import it from salesforce/label module. check below.
import labelName from '@salesforce/label/labelApiName';
Example: Accessing custom label in lightning web component
Create custom label in your org. Add Hello_World as Name and "Hellow World! Welcome to salesforcepoint.com" as Value.
customLabelLwc.js
import { LightningElement } from 'lwc';
//importing custom label to 'WELCOME_MESSAGE'
import WELCOME_MESSAGE from '@salesforce/label/c.Hello_World';
export default class CustomLabelLwc extends LightningElement {
message = WELCOME_MESSAGE; //assigning WELCOME_MESSAGE value to "message" property
}
This is one of the life cycle hooks in web component JavaScript. connectedCallBack function invokes/fires automatically when a certain lwc component is inserted into web dom. It works like an init handler in the lightning aura component, we can say it is lwc init handler.
Important Points about ConnectedCallBack()
It flows from the parent to child component. I.e if the main component has inner component/child components then, ConnectedCallBack function on parent is invoked first, and then ConnectedCallBack of child lwc component will be fired.
In this function, we can access only host element i.e template.
By using "this.template" we can access the host element.
It's invoked after the constructor hook fired.
If we want to fire any logic on component load (for example dispatching the event, assigning values to properties) then we should use ConnectedCallBack life cycle hook.
Examples for connectedCallBack in LWC
These are the basic example to understand connectedCallback function.
In this example, we need to display the list of contacts on the table. While the table is loading we have to show the spinner.
AccountController
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
}
}
In above example, we make "isSpinner" equal to true in connectedCallback function, so that we will see spinner on the page load. Once page data loaded we turned off spinner by making "isSpinner" equal to false in fetchAccList wired function
In many cases we need button alignment to left, center or right. Event though we used correct slds classes, alignment will be not at expected position. In that cases we need to use "slds-clearfix" class for above div of the button, so that we can able to display lightning button at required place.
Slds CSS class for center alignment: slds-align_absolute-center
Slds CSS class for right alignment: slds-float_right
Slds CSS class for left alignment: slds-float_left
Button Alignment in LWC (Lightning Web Components)
Hello folks, in this post we will see how to add validations in lwc input form and showing error message upon button click (most probably Save operation). In any input form we need to validate user entered data before commuting to database whether it is a insert/ update.
In below example we are going to create Contact form that contains First Name, Last Name, phone, email. Here we need to add validations like Name, email should be mandatory.
If we need to make any field required then we need to mention "required" attribute in lightning-input tag so that we can show error message upon save button click. Once user click on save button, we are validating each filed by querying with the lightning-input. By using checkValidity() function we are checking each values entered in form. If all values are in required format then we can write further logic.
If we don't want standard error message, we can set custom message with the help of below attributes.
message-when-value-missing: Used for assigning custom error message when value missed on required field. message-when-too-short: Used for assigning custom error message when entered value not meeting expected length. For this we need to add one more attribute i.e min-length. message-when-too-long: Used for assigning custom error message when entered value exceeds expected length. For this we need to add one more attribute i.e max-length. message-when-pattern-mismatch: Used for assigning custom error message when entered value not matching the expected pattern. This is used for email, url, phone, password, text. For this we need to add one more attribute i.e "pattern".
Hello guys, as part of salesforce winter 21 release, salesforce introduced Safe Navigation Operator( (?.) to avoid null pointer exceptions in apex. This is very useful feature for developers. If we need to check something (whether it is a object, map, list..) should not be null then we will write (?.) at the end. If the left side of the expression(?.) is null, then right side is not evaluated and result will be null.
Till now we used != null condition to check object is not null like below.
if (object!= null){
string s= object.fieldName;
}
we can write above code by using safe navigation operator like below
string s= object?.fieldName;
Example: In this example we have a accountIdAccountMap, it contains account id as key, account record as value. We need to get name of the account.
string accountName = accountIdAccountMap.get(accId).Name;
// this will return null pointer exception if accId not available in the map.
if account not exist on map we will get null pointer exception because we accessing null object for fetching name.
Traditional approach to avoid above null pointer exception:
Fetching and Displaying Picklist Values In Lightning Web Components (LWC) :
By using "lightning-combobox" tag we can display picklist values in Lwc markp. In Lightning Aura Components if we want to display picklist values, we need to hit apex server and needs write logic to fetch picklist values by using dynamic schema. Even though we are write apex logic, we could not get picklist values based on recordtype name or recordTypeId, every time it shows all the values irrespective of record type. But in lightning web components we have a great privilege that don't need to hit apex for fetching picklist values. In Lwc we can get values based on recordtype name as well.
By importing getPicklistValues or getPicklistValuesByRecordType from "lightning/uiObjectInfoApi" we can get picklist values in LWC JavaScript. recordTypeId is required parameter for both of these functions.
Get picklist values based on recordtypeId In Salesforce LWC component
lwcPicklistWithRecordtype.js
import { LightningElement,wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import STAGE from '@salesforce/schema/Opportunity.StageName';
export default class LwcPicklistWithRecordtype extends LightningElement {
@wire(getPicklistValues,
{
recordTypeId: '01228000000XckuAAC', //pass id dynamically
fieldApiName: STAGE
}
)
stageValues;
}
Get picklist values if we don't have recordtypes in Object In Lightning Web Components (LWC)
If object does not have record type's then use the defaultRecordTypeId property, this can be fetch from getRecordUi or getObjectInfo. See below example.
lwcPicklistWithoutRecordtype.js
import { LightningElement,wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import LeadSource from '@salesforce/schema/Contact.LeadSource';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
export default class LwcPicklistWithoutRecordtypeextends LightningElement {
@wire(getObjectInfo, { objectApiName: CONTACT_OBJECT })
contactInfo;
@wire(getPicklistValues,
{
recordTypeId: '$contactInfo.data.defaultRecordTypeId',
fieldApiName: LeadSource
}
)
leadSourceValues;
}
In this post we are going to see how to use refreshApex() function in Lightning web Components with example. If we need to refresh lwc page data we should use refreshApex. We know that wire provisions data, if we use wire function or wire parameter to display data in front end, that data will not be changed or updated unless input parameters changed which are used in wire. By using refreshApex in lwc we can update wire function or wire parameter data, so that component values will be re-rendered.
We need to import refreshApex function from salesforce/apex class, so that we can use it.
refreshApex lwc example:
In below example we are displaying latest five account records in lwc data table and we have a radio button to select the record. Once we click on Delete button selected record will be deleted from apex database but not on table. So we use refreshApex() function (refreshApex(this.wiredAccountList)) to fetch latest data from server on delete success in deleteRecord function. We created "wiredAccountList" property to assign result of wire function "accList" and this property used in resfreshApex function.
AccountController.cls
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
}
}
Make sure that the input parameter in the refreshApex should be total result of wire function but not only data, i.e in many cases we return { error, data } in wire function and we use data only for refresh apex, in this case refreshApex will not work. We must entire result (check above example where we return result not { error, data } and that is assigned to one dummy variable i.e wiredAccountList and that is used as input parameter for refreshApex().
How to Pass Values From Child to Parent component in LWC
In this post we will see how to pass data from child to parent in Lwc. If we want to fire parent lightning web component function from child LWC component function when child function fired or if we need pass data from child LWC component to parent Lightning web component then we need to use custom events. Unlike aura component we don't to create separate event in lightning web components.
Steps for child to parent communication in LWC:
1. Define a custom event in child lightning web component.
2. Add values (which needs to pass to parent lwc) to event. (optional)
3. Dispatch the event.
Example:
Here eventName is user defined key word for event, which is going to use in child component tag in parent component. Make sure that event name should not be starts with "on" word.
4. Handle event on parent lightning web component with the "oneventname" handler function. Here oneventname is the dispathed event in child component(see above code), 'on' should be added before event name.
5. By using event.detail.variableName we will get value which is passed from child lwc.
Example Scenario for Passing values from Child Lightning web component to Parent Lightning web component.
In Below example we have a child component(lwcChild) where we are showing list of account records. In parent component(lwcParent) we are referring child component. on click of record in table, we are firing custom event and dispatching the event with selected account id and then we are showing details of respective account in parent component.
AccountController.cls
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account WITH SECURITY_ENFORCED LIMIT 10];
}
}
Create new lightning web component: lwcChild lwcChild.js
import { LightningElement, api } from 'lwc';
export default class LwcChild extends LightningElement {
@api accountList;
handleAccountClick(event) {
let selectedAccId = event.currentTarget.getAttribute("data-key");
//custom event
const passEvent = new CustomEvent('accountselection', {
detail:{recordId:selectedAccId}
});
this.dispatchEvent(passEvent);
}
}