0% found this document useful (0 votes)
6 views155 pages

LWC Scenarios

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 155

Lightning Web Component

Scenario 1:
Create a UI using Record Form through which we can create an Account Record
and Redirect to a newly created record.

HTML

<template>
<lightning-card>
<lightning-record-form
object-api-name={account}
fields={accfields}
record-id={recordId}
onsuccess={redirecttoAccount}>
</lightning-record-form>
</lightning-card>
</template>

JS
import { LightningElement,api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import ACCOUNT_OBJECT from "@salesforce/schema/Account";
import NAME_FIELD from "@salesforce/schema/Account.Name";
import WEBSITE_FIELD from "@salesforce/schema/Account.Website";
import ANNUALREVENUE_FIELD from
"@salesforce/schema/Account.AnnualRevenue";
import FAX_FIELD from "@salesforce/schema/Account.Fax";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
export default class CreateAccountRecord extends
NavigationMixin(LightningElement) {
@api recordId; //it is used to store recordId
account=ACCOUNT_OBJECT;

accfields=[NAME_FIELD,WEBSITE_FIELD,ANNUALREVENUE_FIELD,FAX_FIELD,INDUSTRY
_FIELD];

Page 1
redirecttoAccount(event){
//this is used to navigate to newly created record
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: event.detail.id,
actionName: 'view'
}
});
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Note: You can place this component on any page like Home Page, App Page or
Record Page to create an account record.

Page 2
Output Screenshot

Page 3
Scenario 2:
Show list of objects like Account, Contact, Case and Opportunity and based on
object selection show the UI of that particular object and create a record. Also
redirect to a new record.

HTML
<template>
<lightning-card>
<lightning-combobox
label="Select Object"
value={selectedObject}
options={objectOptions}
onchange={objectChange}
>

</lightning-combobox>
//lightning-combobox allows a user to select an option from predefined
//list of options that is functionally similar to an HTML select
//element.
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';

export default class ShowObjectsPicklist extends LightningElement {


selectedObject;
objectOptions=[
{ label: 'Account', value: 'Account' },
{ label: 'Contact', value: 'Contact' },
{ label: 'Case', value: 'Case' },
{ label: 'Opportunity', value: 'Opportunity' }

];
objectChange(event){
this.selectedObject=event.detail.value;
switch(this.selectedObject){
//The window. location. href property returns the URL
(Universal Resource Locator) of the current page.
case 'Account':

Page 4
window.location.href='https://sgts87-dev-
ed.develop.lightning.force.com/lightning/o/Account/new?
count=1&nooverride=1&useRecordTypeCheck=1&navigationLocation=LIST_VIEW&uid
=170610923132031006&backgroundContext=%2Flightning%2Fo%2FAccount%2Flist
%3FfilterName%3DRecent';
break;
case 'Contact':
window.location.href='https://sgts87-dev-
ed.develop.lightning.force.com/lightning/o/Contact/new?
count=1&nooverride=1&useRecordTypeCheck=1&navigationLocation=LIST_VIEW&uid
=170473025442610234&backgroundContext=%2Flightning%2Fo%2FContact%2Flist
%3FfilterName%3DRecent';
break;
case 'Case':
window.location.href='https://sgts87-dev-
ed.develop.lightning.force.com/lightning/o/Case/new?
count=1&nooverride=1&useRecordTypeCheck=1&navigationLocation=LIST_VIEW&uid
=170473059065327278&backgroundContext=%2Flightning%2Fo%2FCase%2Flist
%3FfilterName%3DRecent';
break;
case 'Opportunity':
window.location.href='https://sgts87-dev-
ed.develop.lightning.force.com/lightning/o/Opportunity/new?
count=2&nooverride=1&useRecordTypeCheck=1&navigationLocation=LIST_VIEW&uid
=170473037090656137&backgroundContext=%2Flightning%2Fo%2FOpportunity
%2Flist%3FfilterName%3DRecent';
break;
default:
break;
}
}

CS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

Page 5
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 3:

Page 6
Create Account along with Contact Record using LDS (createRecord)

HTML
<template>
<lightning-record-form
object-api-name={account}
fields={accfields}
onsuccess={createrelConRecord}>
</lightning-record-form>
</template>

JS
import { LightningElement ,api} from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from "@salesforce/schema/Account";
import NAME_FIELD from "@salesforce/schema/Account.Name";
import WEBSITE_FIELD from "@salesforce/schema/Account.Website";
import DESCRIPTION_FIELD from "@salesforce/schema/Account.Description";
import FAX_FIELD from "@salesforce/schema/Account.Fax";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
export default class CreateAccrelContact extends LightningElement {
account=ACCOUNT_OBJECT;
accfields=[NAME_FIELD,WEBSITE_FIELD,DESCRIPTION_FIELD,FAX_FIELD,
INDUSTRY_FIELD];

createrelConRecord(event){
//const accountId=event.detail.id;

const createconRec ={
apiName:'Contact',
fields:{
FirstName:'Rel',
LastName:'Contact',
AccountId:event.detail.id
}
};
createRecord(createconRec)
.then(result => {
console.log('Contact created with ID:', result.id);
})

Page 7
// Handle success if needed
.catch(error => {
console.error('Error creating Contact:', error);
});
}

CS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 4:

Page 8
Data Table to show the account records. Account Name should be clickable and
redirect to the respective record.

HTML

<template>
<h2>Account</h2>
<template if:true={accountList}>
<lightning-datatable
key-field="id"
data={accountList}
columns={columns}
hide-checkbox-column="true"
onrowaction={handleRowAction}>

</lightning-datatable>
</template>
</template>

JS
import { LightningElement,wire,api } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts'
import { NavigationMixin } from 'lightning/navigation';
export default class CreateAccountRecord extends
NavigationMixin(LightningElement){
columns=[
{
label:'Name',
type:'button',
typeAttributes:{ label: { fieldName: 'Name' }, name: 'gotoAccount',
variant: 'base' }
},
{label: 'Phone', fieldName: 'Phone', type: 'phone', sortable: true},
{label: 'Website', fieldName: 'Website', type: 'url',

sortable: true},

Page 9
{label: 'AnnualRevenue', fieldName: 'AnnualRevenue', type: 'Currency',

sortable: true}
]
@api recordId;
accountList;
//used to store the data comes form apex
@wire(getAccounts)
wiredAccounts({data,error}){
if(data){
this.accountList=data;
}
else if(error){
console.log(error);
}
}
handleRowAction(event){
const actionName=event.detail.action.name;
const row=event.detail.row;
switch(actionName){
case 'gotoAccount':
this.showAccountpage(row);
break;
default:
}
}
showAccountpage(row){
this.record=row;
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.record.Id,
objectApiName: 'Account', // objectApiName is optional
actionName: 'view'
}
});
}
}

CSS

Page 10
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 5:
Create Account along with Contact Record. Fetch Account and Contact
information from User.

Page 11
HTML

<template>
<lightning-card title="Create Account along with related Contact">
<template lwc:if={showAccountForm}>
<lightning-record-form
object-api-name="Account"
fields={accountFields}
onsuccess={handleSuccess}>
</lightning-record-form>
</template>
<template lwc:if={accountId}>
<lightning-record-form
object-api-name="Contact"
fields={contactFields}
onsubmit={handleContactSubmit}
></lightning-record-form>
</template>
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
export default class CreateAccountandRelatedContactUserInput extends
LightningElement {
accountId;
showAccountForm = true;
accountFields = ['Name','Phone'];
contactFields = ['FirstName', 'LastName'];
handleSuccess(event) {
console.log(event.detail.id,);
this.accountId = event.detail.id;
this.showAccountForm = false;
}

handleContactSubmit(event) {
event.preventDefault(); // stop the form from submitting

Page 12
const fields = event.detail.fields;
fields.AccountId = this.accountId // modify a field

//below statement forcefully submit the form


this.template.querySelector('lightning-record-form').submit(fields);
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 6:
Launch LWC using Quick Actions. Action should be on the Account record page
and will create new contact related to the account.

Page 13
(Use of LDS and Toast Message)

HTML

<template>
<template if:true={closeFormaftercreation}>
<lightning-card title="Create Related Contact">
<div class="slds-p-around_medium">
<lightning-input label="First Name" value={firstName}
onchange={contactChangeVal}></lightning-input>
<lightning-input label="Last Name" value={lastName}
onchange={contactChangeVal}></lightning-input>
<lightning-input label="Email" value={emailId}
onchange={contactChangeVal} ></lightning-input>
<lightning-button label="Save" variant="brand"
onclick={insertContactRecord}></lightning-button>
</div>
</lightning-card>
</template>
</template>

import { LightningElement,api,track} from 'lwc';


import { createRecord } from 'lightning/uiRecordApi';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateContactRecordQuickAction5 extends
LightningElement {
closeFormaftercreation=true;
firstName='';
lastName='';
emailId='';
@api recordId;
contactChangeVal(event){
if(event.target.label=='First Name'){
this.firstName=event.target.value;
}
if(event.target.label=='Last Name'){

Page 14
this.lastName=event.target.value;
}
if(event.target.label=='Email'){
this.emailId=event.target.value;
}
}
insertContactRecord(){
const fields={
AccountId: this.recordId,
FirstName: this.firstName,
LastName: this.lastName,
Email: this.emailId
};
const recordInput = {apiName: CONTACT_OBJECT.objectApiName,
fields }
createRecord(recordInput)
.then(result => {
this.contactId=result.id;
console.log('Contact created with ID:', result.id);
// Show a success toast
const toastEvent = new ShowToastEvent({
title: 'Success',
message: 'Contact created successfully',
variant: 'success'
});
this.dispatchEvent(toastEvent);
})
.catch(error => {
console.error('Error creating Contact:', error);
// Show an error toast
const toastEvent = new ShowToastEvent({
title: 'Error',
message: 'Error creating contact: ' +
error.body.message,
variant: 'error'
});
this.dispatchEvent(toastEvent);
});

this.closeFormaftercreation=false;

Page 15
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>Action</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Output Screenshot

Scenario 7:
Simple Calculator using LWC

HTML

Page 16
<template>
<lightning-card title="Calculator">
<div class="slds-p-around_small">
<lightning-input label = "Enter Number 1" name = "value1"
type = "Number" value = {num1}
onchange={InputChangeHandler}></lightning-input>
<lightning-input label = "Enter Number 2" name = "value2"
type = "Number" value = {num2}
onchange={InputChangeHandler}></lightning-input>
</div>
<div class="slds-m-top_small slds-m-bottom_medium ">
<b>Output = {result}</b>
</div>
<div class="slds-m-top_small slds-m-bottom_medium">
<lightning-button variant="Brand" label="Addition"
onclick={handleClick}
class="slds-m-left_x-small">
</lightning-button>
<lightning-button variant="Brand" label="Substract"
onclick={handleClick}
class="slds-m-left_x-small">
</lightning-button>
<lightning-button variant="Brand" label="Multiply"
onclick={handleClick}
class="slds-m-left_x-small">
</lightning-button>
<lightning-button variant="Brand" label="Divide"
onclick={handleClick}
class="slds-m-left_x-small">

</lightning-button>
</div>
</lightning-card>
</template>

JS

Page 17
import { LightningElement} from 'lwc';

export default class SimpleCalculator extends LightningElement {


result;
num1;
num2;
InputChangeHandler(event){
const name = event.target.name;
if(name === 'value1'){
this.num1 = event.target.value;
}else if(name === 'value2'){
this.num2 = event.target.value;
}
}
handleClick(event){
debugger;
const mathoperator = event.target.label;
const numb1 = parseInt(this.num1, 10);
const numb2 = parseInt(this.num2, 10);
var resulttemp = 0;
if(mathoperator === 'Addition'){
resulttemp = numb1 + numb2;
}else if(mathoperator === 'Substract'){
resulttemp = numb1 - numb2;
}else if(mathoperator === 'Multiply'){
resulttemp = numb1 * numb2;;
}else if(mathoperator === 'Divide'){
resulttemp = numb1 / numb2;;
}

this.result = resulttemp;
}
}

CSS
NIL

XML

Page 18
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 8:
Access Salesforce Image from Static Resource and show it in LWC.

PRE-Steps

Page 19
Create a Static Resource:

● Go to the Salesforce Setup page.


● Search for and select "Static Resources" in the Quick Find box.
● Click on "New Static Resource."
● Provide a name for the static resource, upload the file, and specify the file's MIME
type (e.g., application/javascript, image/png).
● Click "Save" to create the static resource.

HTML

<template>
<lightning-card>
<img style="max-height: 200px" alt="Flower" src={Flower}/>
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
import MY_STATIC_RESOURCE from '@salesforce/resourceUrl/Sun_Flower';
export default class AccessStaticResource extends LightningElement {
Flower=MY_STATIC_RESOURCE;
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Scenario 9:
Upon Clicking of the button show Salesforce Content Asset Files using LWC.

PRE-Steps
1. Search for “Files” in App Launcher, go to Libraries | Asset Library.

Page 20
2. Click Upload Asset File. The file selector opens to let you upload a new file or
select an existing file to make into an asset.
3. After you select a file, a dialog window displays these fields:
● Asset File Name - On this screen, this field displays the API Name. After
you click Save, this field displays the name of the file that you uploaded.
● API Name - The unique name of the asset file in the API, also known as
the developer name

HTML
<template>
<lightning-card>
<lightning-button variant="brand" label="SGTS" title="Primary
action" onclick={handleClick} class="slds-m-left_x-small"></lightning-
button>
<template lwc:if={showimage}>
<div class="slds-m-around_medium">
<img src={SGTS} />
</div>
</template>
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
import myContentAsset from "@salesforce/contentAssetUrl/sanjayguptajpg";
export default class AccessContentAssertFile extends LightningElement {
showimage=false;
SGTS;
handleClick(event){
this.showimage=true;
this.SGTS=myContentAsset;
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>

Page 21
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 10:
Using SVG Resources create a Rectangle and circle inside the rectangle in
LWC(using HTML)

HTML
<template>

Page 22
<!-- You can add an SVG resource to your component in two ways. Add it
directly to your component's HTML template.
Upload the SVG resource as a static resource and import it in your
component's JavaScript file. -->
<!-- this is how we can directly add to HTML component -->
<svg version="1.1" baseProfile="full" width="300" height="200"
xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="blue"></rect>
<circle cx="150" cy="100" r="80" fill="black"></circle>
<text x="150" y="120" font-size="40" text-anchor="middle"
fill="white">SGTS</text>
</svg>
</template>

JS
import { LightningElement } from 'lwc';

export default class UseofSVG extends LightningElement {}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 23
Scenario 11:

Page 24
Using SVG Resources create a Custom Icon and show it in LWC(using Static
resource)

PRE-Steps
1. Write the SVG code into any text Editor and save as with extension .svg
Code:
<svg id="sfdclogo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M14 7L21 12L14 17"/>
<path d="M2 12L14 12"/>
</svg>
2. Upload this file as a Static resource in Salesforce Org.

HTML
<template>
<lightning-card>
<!-- this is how we can directly write SVG code and use as Static
Resource -->
<div class="custom-icon-container">
<img src={customIconUrl} alt="Custom Icon" />
</div>
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
import customIcon from '@salesforce/resourceUrl/Icon';
export default class UseofSVGuisngsr extends LightningElement {
customIconUrl=customIcon;
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>

Page 25
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 12:

Page 26
On click of Button show one Lightning card using Salesforce Custom Labels in
LWC

PRE-Steps
● Click Setup.
● In the User Interface, type Custom Labels.
● Click on the New Custom Label button.
● Enter Short Description; the Name will auto-populate.
● Now enter the text you want to display in the Value.
● Click Save.

HTML
<template>
<!-- Custom labels are custom text values that can be translated into any
language that Salesforce supports. -->
<lightning-button label={label.buttonname} onclick={handleClick}>
</lightning-button>
<template lwc:if={showtext}>
<lightning-card title={label.lightningcardname}></lightning-card>
</template>
</template>

JS
import { LightningElement } from 'lwc';
import lightningcardname from '@salesforce/label/c.LightiningTitle';
import buttonname from '@salesforce/label/c.buttonCL';
export default class UseofCustomlabel extends LightningElement {
showtext= false;
label ={lightningcardname,buttonname}
handleClick(){
this.showtext=true;
}

XML
<?xml version="1.0" encoding="UTF-8"?>

Page 27
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 13:
Show Current/Logged in User Information in LWC

Page 28
HTML
<template>
<lightning-card variant="Narrow" title="Get Current User Info in
LWC" icon-name="standard:user">
<div class="slds-box slds-m-around_medium">
<p><b>User Id :</b> {userId}</p>
<p><b>User Name :</b> {currentUserName}</p>
<p><b>User Email :</b> {currentUserEmail}</p>
<p><b>User Is Active :</b> {currentIsActive}</p>
<p><b>User Alias :</b> {currentUserAlias}</p>
</div>
</lightning-card>
</template>

JS
import { LightningElement, wire } from 'lwc';
//We use ID property to fetch Current User Id
import Id from '@salesforce/user/Id';
import { getRecord } from 'lightning/uiRecordApi';
import UserNameFIELD from '@salesforce/schema/User.Name';
import userEmailFIELD from '@salesforce/schema/User.Email';
import userIsActiveFIELD from '@salesforce/schema/User.IsActive';
import userAliasFIELD from '@salesforce/schema/User.Alias';
export default class GetCureentuserInfo extends LightningElement {
error;
userId = Id;
currentUserName;
currentUserEmail;
currentIsActive;
currentUserAlias;
@wire(getRecord,{recordId:Id,fields:
[UserNameFIELD,userEmailFIELD,userIsActiveFIELD,userAliasFIELD]})
currentUserInformation({error,data}){
if(data){
this.currentUserName = data.fields.Name.value;
this.currentUserEmail = data.fields.Email.value;
this.currentIsActive = data.fields.IsActive.value;

Page 29
this.currentUserAlias = data.fields.Alias.value;
}
else if(error){
this.error=error;
}
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Scenario 14:

Page 30
Show list of objects like Account, Contact, Case and Opportunity and based on
object selection show the Custom UI of that particular object and create a record.
Also redirect to new record

HTML
<template>
<lightning-card title="Select Object">
<lightning-combobox
label="Select Object"
value={selectedObject}
options={ObjectOptions}
onchange={ObjectChange}
>
</lightning-combobox>
</lightning-card>
<template if:true={selectedObject}>
<lightning-card>
<lightning-record-form
object-api-name={selectedObject}
onsuccess={handleRecordCreated}
onerror={handleError}
fields={fieldsCollection}
mode="edit">
</lightning-record-form>
</lightning-card>
</template>
</template>

JS
import { LightningElement,track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class ShowObjectsPicklist extends
NavigationMixin(LightningElement){
selectedObject;
ObjectOptions=[
{ label: 'Account', value: 'Account' },
{ label: 'Contact', value: 'Contact' },

Page 31
{ label: 'Case', value: 'Case' },
{ label: 'Opportunity', value: 'Opportunity' }

];
fieldsCollection=[];
ObjectChange(event) {
this.selectedObject = event.detail.value;
this.loadFields();
}
loadFields(){
switch (this.selectedObject) {
case 'Account':
this.fieldsCollection = ['Name', 'Industry', 'Type'];
break;
case 'Contact':
this.fieldsCollection = ['FirstName', 'LastName',
'Email'];
break;
case 'Opportunity':
this.fieldsCollection=['Name','StageName','CloseDate'];
break;
case 'Case':
this.fieldsCollection=['Status','Origin','Subject'];
break;
default:
this.fieldsCollection = [];
}
}
handleRecordCreated(event){
const recordId = event.detail.id;
this.navigateToRecordPage(recordId);

}
handleError(event) {
console.error('Error creating record:', event.detail.message);
}

navigateToRecordPage(recordId) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',

Page 32
attributes: {
recordId: recordId,
actionName: 'view'
}
});
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 33
Scenario 15:
Create a Currency Converter (EUR to USD and vice versa) using LWC

Page 34
HTML
<template>
<lightning-card title="Currency Converter">
<div class="slds-m-around_medium">
<lightning-input label="Amount" type="number" value={amount}
onchange={handleAmountChange}></lightning-input>
<lightning-combobox label="From Currency" value={fromCurrency}
options={currencyOptions} onchange={handleFromCurrencyChange}></lightning-
combobox>
<lightning-combobox label="To Currency" value={toCurrency}
options={currencyOptions} onchange={handleToCurrencyChange}></lightning-
combobox>
<div class="slds-m-top_medium">Converted Amount:
{convertedAmount}</div>
</div>
</lightning-card>
</template>

JS
import { LightningElement } from 'lwc';
export default class CurrencyConverter extends LightningElement {
amount = 1;
fromCurrency = 'USD';
toCurrency = 'EUR';
convertedAmount = this.convertCurrency(this.amount, this.fromCurrency,
this.toCurrency);

currencyOptions = [
{ label: 'US Dollar (USD)', value: 'USD' },
{ label: 'Euro (EUR)', value: 'EUR' },
// Add more currencies as needed
];

handleAmountChange(event) {
this.amount = event.target.value;
this.convertAndDisplay();
}

Page 35
handleFromCurrencyChange(event) {
this.fromCurrency = event.detail.value;
this.convertAndDisplay();
}

handleToCurrencyChange(event) {
this.toCurrency = event.detail.value;
this.convertAndDisplay();
}

convertAndDisplay() {
this.convertedAmount = this.convertCurrency(this.amount,
this.fromCurrency, this.toCurrency);
}

convertCurrency(amount, fromCurrency, toCurrency) {


// Define fixed exchange rates (example rates, replace with actual
rates)
const exchangeRates = {
'USD': 1,
'EUR': 0.85,
// Add more rates as needed
};

// Perform currency conversion


const convertedAmount = (amount / exchangeRates[fromCurrency]) *
exchangeRates[toCurrency];

// Round to two decimal places


return Math.round(convertedAmount * 100) / 100;
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>

Page 36
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 16:

Page 37
Create a Account through Home Page and Button on Account List View Page
[Using Apex]

HTML
<template>
<lightning-card title="Create Account using Apex Controller" icon-
name="standard:account" >
<p class="slds-p-horizontal_small">
<lightning-input type="text" label="Name"
value={getAccountRecord.Name} onchange={nameInpChange}></lightning-input>
</p>

<p class="slds-p-horizontal_small">
<lightning-input type="text" label="Phone"
value={getAccountRecord.Phone} onchange={phoneInpChange}></lightning-
input>
</p>

<p class="slds-p-horizontal_small">
<lightning-input type="text" label="Website"
value={getAccountRecord.Website} onchange={websiteInpChange}></lightning-
input>
</p>

<p class="slds-p-horizontal_small">
<lightning-input type="text" label="Account Site"
value={getAccountRecord.Site} onchange={accSiteChange}></lightning-input>
</p>

<div slot="footer">
<lightning-button label="Save" onclick={saveAccount}
variant="brand"></lightning-button>
</div>

<br/> <br/>
</lightning-card>
</template>

JS

Page 38
import { LightningElement } from 'lwc';
import insertAccountRecords from
'@salesforce/apex/CreateRecord.insertAccountRecords';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
import SITE_FIELD from '@salesforce/schema/Account.Site';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
//Used to Show toast message on insertion of record
export default class CreateAccountthroughHomePage7 extends
LightningElement {
accountId;
error;
getAccountRecord={
Name: NAME_FIELD,
Phone: PHONE_FIELD,
Website: WEBSITE_FIELD,
Site: SITE_FIELD

};
nameInpChange(event){
this.getAccountRecord.Name=event.target.value;
}
phoneInpChange(event){
this.getAccountRecord.Phone=event.target.value;
}
websiteInpChange(event){
this.getAccountRecord.Website=event.target.value;
}
accSiteChange(event){
this.getAccountRecord.Site=event.target.value;
}
saveAccount(){
insertAccountRecords({accObj:this.getAccountRecord})
.then(result=>{
this.getAccountRecord={};
this.accountId=result.Id;

const toastEvent = new ShowToastEvent({


title:'Success',

Page 39
message:'Account created successfully',
variant:'success'
});
this.dispatchEvent(toastEvent);
})
.catch(error=>{
this.error=error.message;
window.console.log(this.error);
});
}
}

APEX Class:
public with sharing class CreateRecord {
@AuraEnabled
public static Account insertAccountRecords(Account accObj) {
try {
insert accObj;
return accObj;
} catch (Exception exp) {
throw new AuraHandledException(exp.getMessage());
}
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Page 40
Reference to create a Button on ListView Page:

https://www.youtube.com/watch?app=desktop&v=lpAOjK2zVc4

Output Screenshot

Scenario 17:

Page 41
Check Duplicate records. If found then show a toast message, then a screen
which will ask the user whether to update or not. If a duplicate is not found then
create a new record.

HTML
<template>
<lightning-card title="Check Duplicate Account">
<div class="slds-m-around_medium">
<lightning-input label="Account Name" value={accountName}
onchange={handleInputChange}></lightning-input>
<lightning-button label="Check for Duplicates"
onclick={handleCheckDuplicates}></lightning-button>

<template if:true={duplicateAccount}>
<div class="slds-m-top_medium">
<p>Duplicate Account Found!</p>
<p>Existing Account Details:</p>
<ul>
<li><b>Name:</b> {duplicateAccount.Name}</li>
<!-- Add more fields as needed -->
</ul>
<lightning-input label="New Account Name"
value={newAccountName} onchange={handleInputChange}></lightning-input>
<lightning-button label="Update Existing Account"
onclick={handleUpdateExisting}></lightning-button>
</div>
</template>

<template if:false={duplicateAccount}>
<div class="slds-m-top_medium">
<p>No Duplicate Account Found!</p>
<lightning-input label="New Account Name"
value={newAccountName} onchange={handleInputChange}></lightning-input>
<lightning-button label="Create New Account"
onclick={handleCreateNew}></lightning-button>
</div>
</template>
</div>
</lightning-card>
</template>

Page 42
JS
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import checkForDuplicates from
'@salesforce/apex/DuplicateAccount.checkForDuplicates';
import updateExistingAccount from
'@salesforce/apex/DuplicateAccount.updateExistingAccount';
import createNewAccount from
'@salesforce/apex/DuplicateAccount.createNewAccount';

export default class CheckDuplicateAccount extends LightningElement {


existingAccountId;
accountName = '';
newAccountName = '';
duplicateAccount;
handleInputChange(event) {

this.newAccountName = event.target.value;
this.accountName = this.newAccountName;
}

handleCheckDuplicates() {
checkForDuplicates({ accountName: this.accountName })
.then(result => {
if (result) {
// Duplicate found, show details
this.duplicateAccount = result;
this.existingAccountId=result.id;
console.log(this.existingAccountId);
} else {
// No duplicate found
this.duplicateAccount = null;
this.existingAccountId = null;
}
})
.catch(error => {
console.error('Error checking for duplicates: ', error);
});

Page 43
}

handleUpdateExisting() {
const accountId = this.existingAccountId;
console.log(accountId);
updateExistingAccount({ accountId: accountId, newAccountName:
this.newAccountName })
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account updated successfully.',
variant: 'success',
})
);
})
.catch(error => {
console.error('Error updating account: ', error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: 'Error updating account.',
variant: 'error',
})
);
});
}

handleCreateNew() {
createNewAccount({ accountName: this.newAccountName })
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'New account created successfully.',
variant: 'success',
})
);
})
.catch(error => {

Page 44
console.error('Error creating new account: ', error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: 'Error creating new account.',
variant: 'error',
})
);
});
}
}

CSS
NIL
APEX Class:

public with sharing class DuplicateAccount {


@AuraEnabled(cacheable=true)
public static Account checkForDuplicates(String accountName) {
List<Account> duplicateAccounts = [SELECT Id
FROM Account
WHERE Name = :accountName
LIMIT 1];
return duplicateAccounts.isEmpty() ? null : duplicateAccounts[0];
}

@AuraEnabled
public static void updateExistingAccount(String accountId, String newAccountName) {
try {
Account accToUpdate = new Account(Id = accountId, Name = newAccountName);
update accToUpdate;
} catch (Exception e) {
throw new AuraHandledException('Error updating account: ' + e.getMessage());
}
}

@AuraEnabled
public static void createNewAccount(String accountName) {
try {
Account newAccount = new Account(Name = accountName);
insert newAccount;
} catch (Exception e) {

Page 45
throw new AuraHandledException('Error creating new account: ' + e.getMessage());
}
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 46
Scenario 18:

Page 47
Create an Account and then show options to create related records.

HTML
<template>
<lightning-card>
<lightning-record-form
object-api-name={account}
fields={accfields}
onsuccess={saveAccountandShowOption}>
</lightning-record-form>
<template if:true={showOption}>
<div class="button-container">
<div class="button-section">
<lightning-button label="Contact"
onclick={handleButtonClickContact}></lightning-button>
</div>
<!-- Create Contact -->

<div class="button-section">
<lightning-button label="Opportunity"
onclick={handleButtonClickOpp}></lightning-button>
</div>

<div class="button-section">
<lightning-button label="Case"
onclick={handleButtonClickCase}></lightning-button>
</div>
</div>
<div if:true={showContact}>
<lightning-input label="Contact First Name"
value={contactFirstName} name="contactFirstName"
onchange={handleInputChange}></lightning-input>
<lightning-input label="Contact Last Name"
value={contactLastName} name="contactLastName"
onchange={handleInputChange}></lightning-input>
<lightning-button label="Save"
onclick={createContact}></lightning-button>
</div>
<div if:true={showOpp}>

Page 48
<lightning-input label="Opportunity Name"
value={opportunityName} name="opportunityName"
onchange={handleInputChange}></lightning-input>
<lightning-input label="Opportunity Amount" type="number"
value={opportunityAmount} name="opportunityAmount"
onchange={handleInputChange}></lightning-input>
<lightning-button label="Save"
onclick={createOpportunity}></lightning-button>
</div>
<div if:true={showCase}>
<lightning-input label="Case Subject" value={caseSubject}
name="caseSubject" onchange={handleInputChange}></lightning-input>
<lightning-button label="Save"
onclick={createCase}></lightning-button>
</div>
</template>
</lightning-card>
</template>

JS
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import ACCOUNT_OBJECT from "@salesforce/schema/Account";
import NAME_FIELD from "@salesforce/schema/Account.Name";
import WEBSITE_FIELD from "@salesforce/schema/Account.Website";
import ANNUALREVENUE_FIELD from
"@salesforce/schema/Account.AnnualRevenue";
import FAX_FIELD from "@salesforce/schema/Account.Fax";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
import { createRecord } from 'lightning/uiRecordApi';

export default class CreateAccountandoptionTocreateRelatedRecord4 extends


NavigationMixin(LightningElement) {
showContact=false;
showCase=false;
showOpp=false;
showOption=false;
caseSubject = '';

Page 49
contactFirstName = '';
contactLastName = '';
opportunityName = '';
opportunityAmount = 0;

accountId;
account=ACCOUNT_OBJECT;

accfields=[NAME_FIELD,WEBSITE_FIELD,ANNUALREVENUE_FIELD,FAX_FIELD,INDUSTRY
_FIELD];
saveAccountandShowOption(event){
this.showOption=true;
this.showContact = false;
this.showOpp = false;
this.showCase = false;
this.accountId = event.detail.id;
console.log('Account created with Id:', this.accountId);
}
handleButtonClickContact(){
this.showContact=true;
this.showCase=false;
this.showOpp=false;
}
handleButtonClickOpp(){
this.showOpp=true;
this.showContact=false;
this.showCase=false;
}
handleButtonClickCase(){
this.showCase=true;
this.showOpp=false;
this.showContact=false;
}
handleInputChange(event) {
const { name, value } = event.target;
this[name] = value;
console.log("this[name]",event.target.name);
}
createCase() {
this.createRecord('Case', {

Page 50
Subject: this.caseSubject,
AccountId: this.accountId
});
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.accountId,
actionName: 'view'
}
});
}
createContact() {
this.createRecord('Contact', {
FirstName: this.contactFirstName,
LastName: this.contactLastName,
AccountId: this.accountId
});
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.accountId,
actionName: 'view'
}
});
}
createOpportunity() {
this.createRecord('Opportunity', {
Name: this.opportunityName,
Amount: this.opportunityAmount,
CloseDate: new Date(),
StageName: 'Prospecting',
AccountId: this.accountId
});
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.accountId,
actionName: 'view'
}
});

Page 51
}
createRecord(objectApiName, fields) {
//console.log(this.objectApiName);
const recordInput = { apiName: objectApiName, fields };
console.log("recordInput",recordInput);
createRecord(recordInput)
.then((record) => {
console.log('${objectApiName} created with Id:',
record.id);
// You can add further logic or UI updates here
})
.catch((error) => {
console.error('Error creating ${objectApiName}:',
error.body.message);
});
}
}

CSS
.button-container {
display: flex;
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 52
Page 53
Scenario 19:
Through Search box users can search account records and the record user selects,
show its details below. Now if a user updates the data then it should be updated in org.
[Wire Apex]

HTML
<template>
<lightning-card title="Account Search">
<lightning-input type="search" label="Search Accounts"
onchange={handleSearch}></lightning-input>
<template if:true={accounts}>
<template for:each={accounts} for:item="account">
<div key={account.Id}>
<button class="slds-button slds-button_link" data-
id={account.Id} onclick={handleSelectAccount}>{account.Name}</button>
</div>
</template>
</template>
</lightning-card>

<lightning-card if:true={selectedAccount} title="Account Details">


<lightning-record-edit-form object-api-name="Account" record-
id={selectedAccount.Id} onsuccess={handleSuccess}>
<lightning-messages></lightning-messages>

Page 54
<lightning-input-field field-name="Name" name="Name"
onchange={handleInputChange}></lightning-input-field>
<lightning-input-field field-name="Phone" name="Phone"
onchange={handleInputChange}></lightning-input-field>
<!-- Add more fields as needed -->
<div class="slds-m-top_small">
<lightning-button variant="brand" type="submit"
label="Save"></lightning-button>
</div>
</lightning-record-edit-form>
</lightning-card>
</template>

JS
import { LightningElement, track, wire } from 'lwc';
import searchAccounts from
'@salesforce/apex/AccountController.searchAccounts';
import updateAccount from
'@salesforce/apex/AccountController.updateAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
export default class AccountSearch extends
NavigationMixin(LightningElement) {
@track searchTerm = '';
@track accounts;
@track selectedAccount;
accountId;
handleSearch(event) {
this.searchTerm = event.target.value;
console.log(this.searchTerm);
}

@wire(searchAccounts, { searchTerm: '$searchTerm' })


wiredAccounts({ error, data }) {
if (data) {
this.accounts = data;
console.log(data);
} else if (error) {

Page 55
console.error('Error fetching accounts:', error);
}
}

handleSelectAccount(event) {
this.accountId = event.currentTarget.dataset.id;
console.log(this.accountId);
//USe of "find" in the handleSelectAccount method,
//it's used to find the account object in the accounts array whose
Id matches the accountId obtained from the button click event.
this.selectedAccount = this.accounts.find(account => account.Id
=== this.accountId);

}
handleInputChange(event){
console.log('Field Name:', event.target.name);
console.log('Field Value:', event.target.value);
//the handleInputChange method uses the spread syntax (...)to
create a new copy of the selectedAccount object with the updated field
value.
//This ensures that the selectedAccount object is updated
correctly
const fieldName = event.target.name;
this.selectedAccount = { ...this.selectedAccount, [fieldName]:
event.target.value };
}

handleSuccess(event) {
// Display success message or handle other actions
updateAccount({ account: this.selectedAccount })
.then(() => {
const toastEvent = new ShowToastEvent({
title:'Success',
message:'Account Updated successfully',
variant:'success'
});
this.dispatchEvent(toastEvent);
// Optionally perform actions upon successful update

Page 56
})
.catch(error => {
console.error('Error updating account:', error);
// Optionally handle error
});
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: event.detail.id,
actionName: 'view'
}
});
}
}

CSS
NIL
APEX Class:

public with sharing class AccountController{


@AuraEnabled(cacheable=true)
public static List<Account> searchAccounts(String searchTerm) {
String strKey = '%'+searchTerm+'%';
List<Account> blanklist = new List<Account>();
if (String.isNotBlank(searchTerm)) {
List<Account> newacclist= [SELECT Id, Name FROM Account WHERE Name
LIKE :strKey];
return newacclist;
}
else{
return blanklist;
}
}

@AuraEnabled
public static void updateAccount(Account account) {
update account;
}
}

Page 57
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 58
Scenario 20:
Create a Data table to Show related Contact records on Account Record page using
getRelatedList.Launch this Lwc from QuickAction,Action should be Account Record
page

HTML
<template>
<lightning-card title="Related Contacts">
<lightning-datatable
key-field="Id"
data={Records}
columns={columns}
hide-checkbox-column="true"
show-row-number-column>
</lightning-datatable>
</lightning-card>
</template>

JS
import { LightningElement,api,track,wire } from 'lwc';
import { getRelatedListRecords } from 'lightning/uiRelatedListApi';
//Use this wire adapter to get RelatedList records.
import { getFieldValue } from 'lightning/uiRecordApi';
//getFieldValue: It allows you to retrieve the value of a field from a
record without needing to handle null checks or navigate nested objects
manually.
export default class UseofgetrealtedList extends LightningElement {
@api recordId;
@track Records =[];

Page 59
@track reletedRecords;
columns = [

{ label: 'First Name', fieldName: 'FirstName', editable: false },


{ label: 'Last Name', fieldName: 'LastName', editable: false },
{ label: 'Email', fieldName: 'Email', type: 'email', editable:
false },
{ label: 'Title', fieldName: 'Title', type: 'text', editable: false }
];
@wire(getRelatedListRecords, {
parentRecordId: '$recordId',
relatedListId: 'Contacts',
fields:
['Contact.Id','Contact.FirstName','Contact.LastName','Contact.Email','Cont
act.Title'],
sortBy: ['Contact.FirstName']
})
wiredRecords({data, error}){
//console.log(recordId);
if (data) {
this.Records = data.records.map(record=>({
Id:getFieldValue(record,'Contact.Id'),
FirstName:getFieldValue(record,'Contact.FirstName'),
LastName:getFieldValue(record,'Contact.LastName'),
Email:getFieldValue(record,'Contact.Email'),
Title:getFieldValue(record,'Contact.Title')
}));

}
if (error) {
console.error('Error occurred retrieving records...');
}
}
}

CSS
NIL

XML

Page 60
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Output Screenshot

Scenario 21:
Create a Generic Currency Converter using LWC and API Integration

Pre Steps

Create a Remote Site Setting:


● On the Setup Home page, search for Remote Site Settings in the Quick Find
box and select Remote Site Settings.

Page 61
● Click New Remote Site.
● Enter a name for the remote site.
● (Optional) Enter a brief description for the Genesys Cloud site.
● Enter New Remote Site Url “https://api.apilayer.com”
● Click Save.

Create Account on this Apilayer to call this Api : “https://apilayer.com/”

Reference Link : https://apilayer.com/marketplace/fixer-api?preview=true#details-tab

HTML
<template>
<lightning-card title="Currency Converter"
icon-name="custom:custom14">
<div class="slds-p-around_medium">
<lightning-combobox
name="sourceCurrency"
label="Select Source Currency"
value={sourceCurrency}
placeholder="Select Source Currency"
options={options}
onchange={handleSourceChange}></lightning-combobox>

<div class="row">
<lightning-input name="amount"
label="Enter Amount" value={amount}
onchange={handleAmountChange}></lightning-input>
</div>

<lightning-combobox
name="targetCurrency"
label="Select Target Currency"
value={targetCurrency}
placeholder="Select Target Currency"
options={options}
onchange={handleTargetChange}></lightning-combobox>

<div class="slds-m-top_small slds-m-bottom_medium">


<h2 class="slds-text-heading_small slds-m-bottom_small">
<lightning-button variant="brand"

Page 62
label="Convert" title="Convert"
onclick={handleConvert}></lightning-button>
</h2>
</div>

<div class="row">
<lightning-input name="convertedAmount" label="Converted
Amount"
value={convertedAmount}></lightning-input>
</div>
</div>
</lightning-card>
</template>

JS
import { LightningElement, track } from 'lwc';
import convert from '@salesforce/apex/ExchangeCurrency.convert';

export default class CurrencyConverter extends LightningElement {

sourceCurrency = 'USD';
targetCurrency = 'GBP';
amount = '';
@track convertedAmount;

get options() {
return [
{ label: 'US Dollar', value: 'USD' },
{ label: 'Great Britian Pound', value: 'GBP' },
{ label: 'Indian Rupee', value: 'INR' }
];
}

handleSourceChange(event) {
this.sourceCurrency = event.detail.value;
}

handleTargetChange(event) {

Page 63
this.targetCurrency = event.detail.value;
}

handleAmountChange(event) {
this.amount = event.detail.value;
}

handleConvert(event) {
convert({sourceCurrency:this.sourceCurrency,
targetCurrency:this.targetCurrency,
amount: this.amount}).then(result => {
this.convertedAmount = result;
});
}

CSS
NIL
APEX Class:
public with sharing class ExchangeCurrency{
public ExchangeCurrency() {}

@AuraEnabled(cacheable=true)
public static double convert(string sourceCurrency, string targetCurrency, string amount) {
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
string today = String.valueOf(System.today());
req.setEndpoint('https://api.apilayer.com/fixer/convert?
to='+targetCurrency+'&from='+sourceCurrency+'&amount='+amount+'&date='+today);
req.setMethod('GET');
//Paste your api Key here after creating account
req.setHeader('apikey', 'XXXX');
res = http.send(req);
Map<string, object> responseMap = (Map<string, object>)
JSON.deserializeUntyped(res.getbody());
return (double) responseMap.get('result');
}

Page 64
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 22:
Use lightning Accordion - If any account is expanded then show related contacts in Table format.

HTML
<!-- accordionExample.html -->
<template>
<lightning-card title="Accordion Example" icon-name="custom:custom14">

<lightning-accordion allow-multiple-sections-open={multiple}>
<template if:true={accounts}>

Page 65
<template for:each={accounts} for:item="acc">
<lightning-accordion-section name={acc.Name}
label={acc.Name} key={acc.Id}>

<table border="1" cellspacing="0"


cellpadding="5" style="border-collapse:collapse;" class="tblColPad">
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th> First Name</th>
<th>Phone</th>
</tr>

<template for:each={acc.Contacts}
for:item="con">
<!-- <p key={con.Id}> Contact - {con.Name}
-->

<tr key={con.Id}>
<td>{con.Name}</td>
<td>{con.LastName}</td>
<td>{con.Email}</td>
<td>{con.FirstName}</td>
<td>{con.Phone}</td>

</tr>
</template>
</table>
</lightning-accordion-section>
</template>
</template>
</lightning-accordion>

</lightning-card>
</template>

Page 66
JS
import {LightningElement,api,wire} from 'lwc';
import getAccountData from
'@salesforce/apex/AccountController.getAccountData';
export default class AccordionExample extends LightningElement {
multiple = true;
accounts ;
@wire (getAccountData) getContact;
@wire(getAccountData)
wiredAccountss({
error,
data
}) {
if (data) {
this.accounts = data;
console.log(data);
console.log(JSON.stringify(data, null, '\t'));

data.forEach(function (item, key) {


console.log(key);
console.log(item);
});

} else if (error) {
this.error = error;
}
}

CSS
NIL

APEX Class:
public with sharing class AccountController{
public AccountController() {

Page 67
@AuraEnabled(cacheable=true)
public static List<Account> getAccountData() {
return [SELECT Id,Name,(Select Id,Name,FirstName,LastName,Email,Phone from
Contacts) from Account];
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Scenario 23:
Use Lightning Icon of different Type (Standard, Custom, Utility, Action and DocType)

Page 68
HTML
<template>
<lightning-card title="Lighting Icons">
<p id="action" class="slds-box slds-text-heading_small">Action icons
represent actions a user can take.<br /><br />
<lightning-icon icon-name="action:new_note" alternative-text="New
note" title="New note"></lightning-icon>
<lightning-icon icon-name="action:preview" alternative-
text="Preview" title="Preview"></lightning-icon>
</p>
<p id="doctype" class="slds-box slds-text-heading_small">Doctype icons
represent a type of file when a preview or
image is unavailable. <br /><br />
<lightning-icon icon-name="doctype:audio" alternative-text="Audio
file" title="Audio"></lightning-icon>
<lightning-icon icon-name="doctype:image" alternative-text="Image
file" title="Image"></lightning-icon>
</p>

<p id="standard" class="slds-box slds-text-heading_small">Standard


icons represent entities and objects within
Salesforce. <br /><br />
<lightning-icon icon-name="standard:event" alternative-
text="Event" title="Event"></lightning-icon>
<lightning-icon icon-name="standard:account" alternative-
text="Account" title="Account"></lightning-icon>
</p>

<p id="utility" class="slds-box slds-text-heading_small">Utility icons


are used throughout the interface and are
SVGs for extensibility. <br /><br />
<lightning-icon icon-name="utility:connected_apps" alternative-
text="Connected" title="Connected">
</lightning-icon>
<lightning-icon icon-name="utility:warning" alternative-
text="Warning!" title="Warning"></lightning-icon>
</p>

Page 69
<p id="custom" class="slds-box slds-text-heading_small">Custom icons
are available in Salesforce to represent user
created objects.<br /><br />
<lightning-icon icon-name="custom:custom11"
title="custom11"></lightning-icon>
<lightning-icon icon-name="custom:custom33"
title="custom33"></lightning-icon>
</p>
</lightning-card>
</template>

JS
NIL
CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 70
Scenario 24:
Example of Life Cycle Hooks having Constructor, connectedCallback, renderedCallback,
errorCallback and disconnectedCallback methods defined.

parent.HTML
<template>
<lightning-card title={message}>
<p class="slds-var-p-around_small">
<template if:true={show}>
<c-child onincreasecount={updateMessage}
message="hello"></c-child>
</template>
<lightning-button label="Toggle Child"
onclick={toggleChild}></lightning-button>
</p>
</lightning-card>
</template>

Page 71
parent.JS
import { LightningElement, track } from 'lwc';

export default class Parent extends LightningElement {

message = 'Updated count will appear here!';


show = true;

constructor() {
super();
console.log('Parent constructor called');
}

connectedCallback() {
console.log('Parent connected callback called');
console.log(this.template.querySelector('c-child'));
}

renderedCallback() {
console.log('Parent rendered callback called');
console.log(this.template.querySelector('c-child'));
}

errorCallback(error, stack) {
console.log('Parent error callback called, error = ' +
JSON.stringify(error) + ', stack = ' + stack);
console.log(this.template.querySelector('c-child'));
}

updateMessage(event) {
this.message = event.detail.message;
}

toggleChild() {
this.show = !this.show;
}
}

CSS

Page 72
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

child.HTML
<template>
<lightning-button label="Increase Count"
onclick={increaseCount}></lightning-button>
<br /><br />
</template>

child.JS
import { LightningElement, api } from 'lwc';

export default class Child extends LightningElement {

count = 0;
@api
message = 'default';

constructor() {
super();
console.log('Child constructor called');
console.log(this.count);
console.log(this.message);
console.log(this.template.querySelector('lightning-button'));
}

Page 73
connectedCallback() {
console.log('Child connected callback called');
console.log(this.count);
console.log(this.message);
console.log(this.template.querySelector('lightning-button'));
let error = {
code: 100,
message: 'Error from child connected callback!'
};
throw error;
}

renderedCallback() {
console.log('Child rendered callback called');
console.log(this.template.querySelector('lightning-button'));
}

disconnectedCallback() {
console.log('Child disconnected callback called');
}

errorCallback(error, stack) {
console.log('Child error callback called, error = ' +
JSON.stringify(error) + ', stack = ' + JSON.stringify(stack));
}

increaseCount() {
this.dispatchEvent(new CustomEvent('increasecount', {
detail: {
message: 'Increased count to ' + (++this.count)
}
}));
}
}

CSS
NIL

Page 74
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>

Reference Document : https://www.sfdcstop.com/2023/08/lifecycle-hooks-in-


lwc.html

Output Screenshot

Page 75
Scenario 25:
Create record using Lightning Data Service (LDS)

HTML
<template>
<lightning-card title="Create Account Record" icon-
name="standard:account">
<div style="margin-left: 6%" if:true={error}>
<lightning-badge label={error} style="color: red;"></lightning-
badge>
</div>

<template if:true={accRecord}>
<div class="slds-m-around--xx-large">
<div class="container-fluid">
<div class="form-group">

Page 76
<lightning-input label="Enter Account Name"
name="accName" required="required" type="text" value={accRecord.Name}
onchange={handleNameChange}></lightning-input>
</div>
<div class="form-group">
<lightning-input label="Enter Phone Number"
name="accPhone" type="text" value={accRecord.Phone}
onchange={handlePhoneChange}></lightning-input>
</div>
<div class="form-group">
<lightning-input label="Enter Account Type"
name="accEmail" required="required" type="text" value={accRecord.Type}
onchange={handleTypeChange}></lightning-input>
</div>
<div class="form-group">
<lightning-input label="Enter Industry"
name="accIndustry" type="text" value={accRecord.Industry}
onchange={handleIndustryChange}></lightning-input>
</div>
</div>
<br/>
<lightning-button label="Submit" onclick={handleSave}
variant="brand"></lightning-button>
</div>
</template>
</lightning-card>
</template>

JS
import { LightningElement, api } from 'lwc';
// import uiRecordApi to create record
import { createRecord } from 'lightning/uiRecordApi';
// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
// importing Account fields
import { NavigationMixin } from 'lightning/navigation';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

Page 77
import NAME_FIELD from '@salesforce/schema/Account.Name';
import Phone_FIELD from '@salesforce/schema/Account.Phone';
import Industry_FIELD from '@salesforce/schema/Account.Industry';
import Type_FIELD from '@salesforce/schema/Account.Type';
export default class WireAdapterCreateRec extends
NavigationMixin(LightningElement) {
@api recordId;
error;

// this object have record information


accRecord = {
Name : NAME_FIELD,
Industry : Industry_FIELD,
Phone : Phone_FIELD,
Type : Type_FIELD
};

handleNameChange(event) {
this.accRecord.Name = event.target.value;
}

handlePhoneChange(event) {
this.accRecord.Phone = event.target.value;
}

handleTypeChange(event) {
this.accRecord.Type = event.target.value;
}

handleIndustryChange(event) {
this.accRecord.Industry = event.target.value;
}

handleSave(event) {
const fields = {};

Page 78
fields[NAME_FIELD.fieldApiName] = this.accRecord.Name;
fields[Phone_FIELD.fieldApiName] = this.accRecord.Phone;
fields[Industry_FIELD.fieldApiName] = this.accRecord.Industry;
fields[Type_FIELD.fieldApiName] = this.accRecord.Type;

// Creating record using uiRecordApi


let recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields }
createRecord(recordInput)
.then(result => {
// Clear the user enter values
this.accRecord = {};

// Show success messsage


this.dispatchEvent(new ShowToastEvent({
title: 'Success!!',
message: 'Account Created Successfully!!',
variant: 'success'
}),
);

this[NavigationMixin.Navigate]({
type: "standard__recordPage",
attributes: {
recordId: result.id,
objectApiName: ACCOUNT_OBJECT.objectApiName,
actionName: 'view'
}
});
})
.catch(error => {
this.error = JSON.stringify(error);
});
}
}

XML

Page 79
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>

<targets>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Scenario 26:
Update record using Lightning Data Service (LDS)

HTML
<template>
<lightning-card>
<lightning-input name="name" value={name} label="Account Name"
onchange={handleChange}>

</lightning-input>
<lightning-input name="rating" value={rating} label="Rating"
onchange={handleChange}>

</lightning-input>
<lightning-input name="industry" value={industry} label="Industry"
onchange={handleChange}>

Page 80
</lightning-input>

<lightning-button label="Update" onclick={handleClick}></lightning-


button>
</lightning-card>
</template>

JS
import { LightningElement, api } from 'lwc';
import ACCOUNT_OBJECT from "@salesforce/schema/Account";

import ID_FIELD from "@salesforce/schema/Account.Id";


import NAME_FIELD from "@salesforce/schema/Account.Name";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
import RATING_FIELD from "@salesforce/schema/Account.Rating";

// Import the named import updateRecord


import { updateRecord } from "lightning/uiRecordApi";
// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class UpdateRecordDemo extends LightningElement {

@api recordId;
name;
industry;
rating;

handleChange(e) {
if (e.target.name === "name") {
//this is name input textbox
this.name = e.target.value;
} else if (e.target.name === "industry") {
//this is industry input textbox
this.industry = e.target.value;

Page 81
} else if (e.target.name === "rating") {
//this is rating input textbox
this.rating = e.target.value;
}
}

handleClick() {
//map the data to the fields
const fields = {};

fields[ID_FIELD.fieldApiName] = this.recordId;
fields[NAME_FIELD.fieldApiName] = this.name;
fields[INDUSTRY_FIELD.fieldApiName] = this.industry;
fields[RATING_FIELD.fieldApiName] = this.rating;

//Create a config object that had info about fields.


//Quick heads up here we are not providing Object API Name
const recordInput = {
fields: fields
};

//Invoke the method updateRecord()


updateRecord(recordInput)
.then((record) => {
// Show success messsage
this.dispatchEvent(new ShowToastEvent({
title: 'Success!!',
message: 'Account Updated Successfully!!',
variant: 'success'
}),);
});
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>

Page 82
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>

<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

Scenario 27:
Delete record using Lightning Data Service (LDS)

HTML
<template>
<lightning-button
variant="destructive"
label="Delete"
icon-name="utility:delete"
icon-position="right"
onclick={delete1}>
</lightning-button>
</template>

JS
import { LightningElement, api } from 'lwc';
import { deleteRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { NavigationMixin } from "lightning/navigation";
export default class DeleteRecordDemo extends
NavigationMixin(LightningElement) {

@api recordId;
@api objectApiName;

delete1(event) {
this[NavigationMixin.Navigate]({

Page 83
type: "standard__objectPage",
attributes: {
objectApiName: "Contact",
actionName: "list"

},
state: {
filterName: 'Recent'
}
});

deleteRecord(this.recordId)
.then(() => {
console.log('record is deleted');
})
.catch((error) => {
this.dispatchEvent(
new ShowToastEvent({
title: "Error deleting record",
message: error.body.message,
variant: "error"
}),
);
});
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>

<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

Page 84
Scenario 28:
Get the sObject name from the user to show the records in the Data Table on the home page.

HTML
<template>
<div if:true={showDataTable}>
<lightning-card title="Object Records List">

<lightning-datatable
key-field="Id"
data={fetchedRecord}
columns={columns}
hide-checkbox-column="true">
</lightning-datatable>

</lightning-card>
</div>
</template>

JS
import { LightningElement,api,wire,track } from 'lwc';
import FetchRecords from
'@salesforce/apex/AccountController.FetchRecords';
export default class ObjectRecordsList extends LightningElement {
@api SObject;
@api Fields;
showDataTable = false;
@track columns=[];
@track fetchedRecord;

connectedCallback() {
let fieldsArray = [];
// Check if Fields is not empty before creating columns

if (this.Fields) {

fieldsArray = this.Fields.trim().split(",");

Page 85
console.log('Fields Array:', fieldsArray);
}

this.columns = fieldsArray.map(field => ({


label: field, // Use the field name as the column label
fieldName: field, // Use the field name as the field API name
type: 'string'

}));
this.showDataTable = true;
console.log('Fields columns:', this.columns);
this.fetchData();
}

fetchData() {
FetchRecords({SobjectName:this.SObject,FieldsName:this.Fields})
.then(data => {

this.fetchedRecord = data;
console.log('Fetchrecords',this.fetchedRecord); // Logging fetched
records
})
.catch(error => {
console.error('Error fetching records: ', error);
});
}
}

CSS
NIL

APEX Class:
public with sharing class AccountController{
@AuraEnabled(cacheable = true)
public static List<SObject> FetchRecords(String SobjectName, String FieldsName){
String query = 'select ' + FieldsName + ' From ' + SobjectName;
try {
List<SObject> fetchedRecord = Database.query(query);
system.debug(fetchedRecord);

Page 86
return fetchedRecord;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig
targets="lightning__RecordPage,lightning__AppPage,lightning__HomePage">
<property label="SObject" name="SObject" type="String"
required="true"/>
<property label="Fields" name="Fields" description="Please
Enter Fields you want to See (Comma Seprated)" type="String"
required="true"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Output Screenshot

Pre -Steps:
1. Paste this Lwc on any of the Page(App,Home,Record)
2. After that enter SObject and Fields you want to see in dataTable.

Page 87
Scenario 29:
Override Standard Edit button with LWC component.

HTML
<template>
<lightning-card>
<lightning-record-edit-form record-id={recordId}
object-api-name="Account" onsuccess={handleSubmit}>
<lightning-input-field field-
name="Name"></lightning-input-field>
<lightning-input-field field-
name="Industry"></lightning-input-field>
<lightning-input-field field-
name="Phone"></lightning-input-field>

Page 88
<div class="slds-m-top_medium">
<lightning-button type="submit" label="Save"
variant="brand"></lightning-button>
</div>
</lightning-record-edit-form>
</lightning-card>

</template>

JS
import { LightningElement,api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class OverrideEditButton6 extends LightningElement {
@api recordId;

handleSubmit(event){
console.log(this.recordId);
//event.preventDefault();
const evt = new ShowToastEvent({
title: 'Account Updated',
message: 'Record ID: ' + event.detail.id,
variant: 'success',
});

this.dispatchEvent(evt);
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>

Page 89
<targets>
<target>lightning__RecordPage</target>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Pre -Steps:
1. You cannot call lwc DIrectly through standard buttons of salesforce
2. You need to Wrap your LWC into an Aura component
3. Click on Gear icon >Developer Console> File> New > Lightning
Component.
4. Paste the below code:
<aura:component
implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:act
ionOverride" access="global" >
<aura:attribute name="recordId" type="String"/>
<c:overrideEditButton6 recordId="{!v.recordId}"/>

</aura:component>
Output Screenshot

Page 90
Reference :
https://salesforce.stackexchange.com/questions/283335/how-to-pass-record-id-
from-aura-application-to-lightning-web-component-in-salesf

Scenario 30:
Show contacts related to an account using parent child components. Place parent
component on Account Record Page

child.HTML
<template>
<lightning-card>
<table border="1" cellspacing="0" cellpadding="5" style="border-
collapse:collapse;" class="tblColPad">
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th> Title</th>

</tr>

<template for:each={contacts} for:item="contact">


<tr key={contact.Id}>
<td>{contact.Name}</td>
<td>{contact.Phone}</td>
<td>{contact.Email}</td>
<td>{contact.Title}</td>

</tr>
</template>
</table>

</lightning-card>
</template>

Page 91
child.JS
import { LightningElement, api } from 'lwc';

export default class ContactList extends LightningElement {


@api contacts=[];
}

CSS
NIL

child.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Parent.HTML
<template>
<lightning-card title="Contacts Related to Account" icon-
name="standard:contact">
<div>
<c-contact-list contacts={relatedContacts}></c-contact-list>
</div>
</lightning-card>
</template>

Parent.JS
import { LightningElement, api, track, wire } from 'lwc';

Page 92
import getRelatedContacts from
'@salesforce/apex/AccountController.getRelatedContacts';
export default class AccountWithContacts extends LightningElement {
@api recordId;

@track relatedContacts=[];
@wire(getRelatedContacts, { accountId: '$recordId' })

wiredRecordsMethod({ error, data }) {

if(data) {
console.log(this.data);
this.relatedContacts=data;
}
}

CSS
NIL

Parent.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

APEX:
public with sharing class AccountController{

@AuraEnabled(cacheable=true)
public static List<Contact> getRelatedContacts(Id accountId) {
List<Contact> retList=[SELECT Id, Name,Email,Phone,Title FROM Contact WHERE
AccountId = :accountId];

Page 93
system.debug(retList);
return retList;
}
}

Output Screenshot

Page 94
Scenario 30:
Use of getlistUI(with pageToken)

HTML
<!-- wireListViewToken.html -->
<template>
<lightning-card title="WireListViewToken">
<template lwc:if={records}>
<div class="slds-m-around_medium">
<table border="1" cellspacing="0" cellpadding="5"
style="border-collapse:collapse;" class="tblColPad">
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th> Title</th>

</tr>

Page 95
<template for:each={records} for:item="record">
<tr key={record.fields.Id.value}>
<td>{record.fields.Name.value}</td>
<td>{record.fields.Phone.value}</td>
<td>{record.fields.Email.value}</td>
<td>{record.fields.Title.value}</td>

</tr>
</template>
</table>
</div>
</template>
<div class="slds-grid">
<div class="slds-m-around_medium">
<lightning-button label="Previous"
onclick={handlePreviousPage}></lightning-button>
</div>
<div class="slds-m-around_medium slds-col_bump-left">
<lightning-button label="Next"
onclick={handleNextPage}></lightning-button>
</div>
</div>
</lightning-card>
</template>

JS
import { LightningElement, wire,track } from "lwc";
import { getListUi } from "lightning/uiListApi";
import CONTACT_OBJECT from "@salesforce/schema/Contact";
import NAME_FIELD from "@salesforce/schema/Contact.FirstName";

export default class WireListViewToken extends LightningElement {


pageToken = null;
nextPageToken = null;
previousPageToken = null;
records;
error;

Page 96
@wire(getListUi, {
objectApiName: CONTACT_OBJECT,
listViewApiName: "MyContactsNew",
sortBy: NAME_FIELD,
pageSize: 10,
pageToken: "$pageToken",
})
listView({ error, data }) {
if (data) {
this.records = data.records.records;
this.error = undefined;
this.nextPageToken = data.records.nextPageToken;
this.previousPageToken = data.records.previousPageToken;
} else if (error) {
this.error = error;
this.records = undefined;
}
}

handleNextPage(e) {
this.pageToken = this.nextPageToken;
}

handlePreviousPage(e) {
this.pageToken = this.previousPageToken;
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>

Page 97
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 98
Scenario 31:
Open Modal on click of Button and Create Account record using LDS.

HTML

<template>
<lightning-quick-action-panel header="Create Account">
<lightning-input label="Name" value={accountname}
onchange={handleNameChange}></lightning-input>
<lightning-input type="Phone" label="Phone" value={phone}
onchange={handlePhnChange}></lightning-input><br/>
<lightning-button label="Save" onclick={handleClick}></lightning-
button>
</lightning-quick-action-panel>
</template>

Page 99
JS
import { LightningElement } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class OpenModalForm extends LightningElement {
accountname = '';
phone = '';
accountId;

handleNameChange(event) {
this.accountname = event.target.value;
//console.log("name1", this.rec.Name);
}

handlePhnChange(event) {
this.phone = event.target.value;
//console.log("Phone", this.rec.Phone);
}

handleClick() {
const fields = {
Name: this. accountname,
Phone: this.phone
};
const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName,
fields };
createRecord(recordInput)
.then(account => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account created successfully',
variant: 'success'

Page 100
})
);
this.dispatchEvent(new CloseActionScreenEvent());
// Optionally, perform any other actions after successful
creation
})

.catch(error => {
console.error('Error creating account:', error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating account',
message: error.body.message,
variant: 'error'
})
);
// Optionally, handle error
});

}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Page 101
Reference Document:
https://www.salesforceben.com/create-lightning-web-components-lwc-using-
quick-actions/

Scenario 32:
Launch LWC using quick Action on account record page, on click of button show all contact's
data which is related to parent account of that particular child account. Now user should be able
to add using modal pop up/update using inline editing contacts and upon save identified contacts
should be created related to Account where button is placed.

HTML
<template>
<lightning-card title="Contact List">
<!-- Display contacts related to the parent account -->

Page 102
<template if:true={contacts}>
<lightning-datatable
key-field="Id"
data={contacts}
columns={columns}
onsave={handleSave}
draft-values={saveDraftValues}>
</lightning-datatable>
<div style="display: flex; justify-content: center; padding:
1rem 0;">

<div style="margin-right: 0;">


<lightning-button if:true={contacts} icon-
name="utility:copy" variant="brand" label="Clone Contact"
title="Save Resource Allocations"
onclick={handleClone}></lightning-button>

</div>
</div>
<div><lightning-button label="Add New Contact"
onclick={handleAddContact} variant="brand"></lightning-button></div>
</template>
<!-- Buttons to add, remove, and update contacts -->
<div class="slds-m-top_medium">
<template if:true={showRecordForm}>
<lightning-input label="First Name" value={firstName}
onchange={contactChangeVal}></lightning-input>
<lightning-input label="Last Name" value={lastName}
onchange={contactChangeVal}></lightning-input>
<lightning-input label="Email" value={emailId}
onchange={contactChangeVal} ></lightning-input>
<lightning-button label="Save" variant="brand"
onclick={insertContactRecord}></lightning-button>
</template>
</div>
</lightning-card>
</template>

Page 103
import { LightningElement, api, wire,track } from 'lwc';
import getParentAccountId from
'@salesforce/apex/AccountController.getParentAccountId';
import getContacts from '@salesforce/apex/AccountController.getContacts';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import { createRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { updateRecord } from 'lightning/uiRecordApi';
const columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Email', fieldName: 'Email', type: 'email' ,editable: true },
{ label: 'First Name', fieldName: 'FirstName' },
{ label: 'Last Name', fieldName: 'LastName' },
{ label: 'Phone', fieldName: 'Phone' ,editable: true },
{ label: 'Title', fieldName: 'Title',editable: true },
// Add more columns as needed
];
export default class ContactList extends LightningElement {
showRecordForm=false;
firstName='';
lastName='';
emailId='';
saveDraftValues=[];
@api recordId; // Child Account Id
columns = columns;
@track contacts = [];
fields = [LASTNAME_FIELD, EMAIL_FIELD, FIRSTNAME_FIELD];
parentAccountId;
@wire(getParentAccountId, { childAccountId: '$recordId' })
wiredParentAccountId({ error, data }) {
console.log(this.recordId);
if (data) {
console.log(data);
this.parentAccountId = data;
// Load contacts once the parent account Id is available

Page 104
this.loadContacts();
} else if (error) {
// Handle error
}
}

loadContacts() {
// Use parentAccountId to fetch contacts related to the parent account
getContacts({ getparentAccountId: this.parentAccountId })
.then(result => {
console.log(result);
this.contacts = result;
console.log(this.contacts)
})
.catch(error => {
// Handle error
});
}
handleAddContact(event){
this.showRecordForm=true;
}
contactChangeVal(event){
if(event.target.label=='First Name'){
this.firstName=event.target.value;
}
if(event.target.label=='Last Name'){
this.lastName=event.target.value;
}
if(event.target.label=='Email'){
this.emailId=event.target.value;
}
}
insertContactRecord(event){
const fields={
AccountId: this.recordId,
FirstName: this.firstName,
LastName: this.lastName,
Email: this.emailId
};
const recordInput = {apiName: CONTACT_OBJECT.objectApiName, fields }

Page 105
createRecord(recordInput)
.then(result => {
this.contactId=result.id;
console.log('Contact created with ID:', result.id);
// Show a success toast
const toastEvent = new ShowToastEvent({
title: 'Success',
message: 'Contact created successfully',
variant: 'success'
});
this.dispatchEvent(toastEvent);
})
.catch(error => {
console.error('Error creating Contact:', error);
// Show an error toast
const toastEvent = new ShowToastEvent({
title: 'Error',
message: 'Error creating contact: ' + error.body.message,
variant: 'error'
});
this.dispatchEvent(toastEvent);
});

this.showRecordForm=false;

}
handleClone(){
var selectedRecords = this.template.querySelector("lightning-
datatable").getSelectedRows();
if (selectedRecords.length > 0) {
// Loop through selected rows and create contacts
console.log(selectedRecords);
selectedRecords.forEach(row => {
this.createContactForChildAccount(row);
});
}
}
createContactForChildAccount(row) {
const fields = {
AccountId: this.recordId,

Page 106
FirstName: row.FirstName,
LastName: row.LastName,
Email: row.Email
};
const recordInput = { apiName: CONTACT_OBJECT.objectApiName, fields };
createRecord(recordInput)
.then(result => {
// Show a success toast
const toastEvent = new ShowToastEvent({
title: 'Success',
message: 'Contact created successfully',
variant: 'success'
});
this.dispatchEvent(toastEvent);
})
.catch(error => {
console.error('Error creating Contact:', error);
// Show an error toast
const toastEvent = new ShowToastEvent({
title: 'Error',
message: 'Error creating contact: ' + error.body.message,
variant: 'error'
});
this.dispatchEvent(toastEvent);
});
}

handleSave(event) {
this.saveDraftValues = event.detail.draftValues;
console.log(this.saveDraftValues);
const recordInputs = this.saveDraftValues.slice().map(draft => {
const fields = Object.assign({}, draft);
return { fields };
});

// Updateing the records using the UiRecordAPi


const promises = recordInputs.map(recordInputvar =>
updateRecord(recordInputvar));
Promise.all(promises).then(res => {

Page 107
this.ShowToast('Success', 'Records Updated Successfully!',
'success', 'dismissable');
this.saveDraftValues = [];
return this.refresh();

}).catch(error => {
this.ShowToast('Error', 'An Error Occured!!', 'error',
'dismissable');
}).finally(() => {
this.saveDraftValues = [];
});
//this.dispatchEvent(new CloseActionScreenEvent());
}
ShowToast(title, message, variant, mode){
const evt = new ShowToastEvent({
title: title,
message:message,
variant: variant,
mode: mode
});
this.dispatchEvent(evt);
}

// This function is used to refresh the table once data updated


async refresh() {
await refreshApex(this.contacts);
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>

Page 108
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

Output Screenshot

Page 109
Page 110
Page 111
Scenario 33:
LMS Simple Example

Pre-Steps:
1. Create a folder named ‘messageChannels’ at force-app/main/default
location
2. After the folder is established, the next step involves creating the
initial Lightning message channel XML file, which should have the
“.messageChannel-meta.xml” suffix.
3. And paste this XML in above File.

NewLMS.messageChannel-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>AccountData</masterLabel>
<isExposed>true</isExposed>
<description>This is a channel which is used by LWC component to send data
</description>
<lightningMessageFields>
<description>This is First Name</description>
<fieldName>firstName</fieldName>
</lightningMessageFields>
<lightningMessageFields>
<description>This is Last Name</description>
<fieldName>lastName</fieldName>
</lightningMessageFields>

Page 112
</LightningMessageChannel>

sendData.HTML
<template>
<lightning-card title="Data Transfer Using Message Channel for
Unrelated LWC Component">
<div class = "slds-p-around_medium slds-box">
<lightning-input type="text"
name = "fName"
label="Enter First Name"
value = {firstName}
onchange = {handlefirstName}>
</lightning-input><br/>
<lightning-input type="text"
name = "lName"
label="Enter Last Name"
value = {lastName}
onchange = {handlelastName}>
</lightning-input>
<br/>
<lightning-button variant="brand" label="send data"
onclick={handleClick}>

</lightning-button>
</div>
</lightning-card>

</template>

sendData.JS
import { LightningElement,wire ,api} from 'lwc';
import { publish, MessageContext } from "lightning/messageService";
import NEW_CHANNEL from "@salesforce/messageChannel/NewUsage__c";
export default class SendData extends LightningElement {

@api firstName;
@api lastName;

Page 113
@wire(MessageContext)
messageContext;

handlefirstName(event){
this.firstName = event.target.value;
}
handlelastName(event){
this.lastName = event.target.value;
}
handleClick(){
const messaage = {
firstName: this.firstName,
lastName: this.lastName
};
publish(this.messageContext, NEW_CHANNEL, messaage);
}

CSS
NIL

sendData.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

reciver.HTML
<template>
<lightning-card title="Recived Data Using Message Channel
for Unrelated LWC Component">
<div class="slds-m-around_medium">

Page 114
First Name : <strong>{myfirstName}</strong><br/>
Last Name : <strong>{mylastName}</strong>
</div>
</lightning-card>
</template>

reciver.JS
import { LightningElement,wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import NEW_CHANNEL from "@salesforce/messageChannel/NewUsage__c";
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ReciveData extends LightningElement {

subscription = null;
@wire(MessageContext)
messageContext;

myfirstName = '';
mylastName = '';

connectedCallback() {

this.handleSubscribe();
}

handleSubscribe() {
if (this.subscription) {
return;
}
this.subscription = subscribe(this.messageContext, NEW_CHANNEL,
(message) => {
this.myfirstName = message.firstName;
this.mylastName = message.lastName;
this.ShowToast('Success', 'Data Transfer Successfully', 'success',
'dismissable');
});
}
ShowToast(title, message, variant, mode){

Page 115
const evt = new ShowToastEvent({
title: title,
message:message,
variant: variant,
mode: mode
});
this.dispatchEvent(evt);
}
}

CSS
NIL

reciver.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 116
Reference Document :
https://santanuboral.blogspot.com/2021/02/lms-with-lwc.html

Scenario 34:
Create a Custom file Upload Component which should work for any object also uploaded file will
store in Files object

HTML
<template>
<lightning-card title="File Upload Demo LWC" icon-
name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input type="file"
accept=".xlsx, .xls, .csv, .png, .doc, .docx, .pdf"
label="Attachment" onchange={openfileUpload}></lightning-
input>
</div>
<template if:true={fileData}>
<p>{fileData.filename}</p>
</template>
<lightning-button variant="brand" label="submit" title="Submit"
onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
</lightning-card>
</template>

JS
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/AccountController.uploadFile'
export default class FileUploaderCompLwc extends LightningElement {
@api recordId;
fileData
openfileUpload(event) {
const file = event.target.files[0]
var reader = new FileReader()
reader.onload = () => {
var base64 = reader.result.split(',')[1]
this.fileData = {
'filename': file.name,

Page 117
'base64': base64,
'recordId': this.recordId
}
console.log(this.fileData)
}
reader.readAsDataURL(file)
}

handleClick(){
const {base64, filename, recordId} = this.fileData
uploadFile({ base64, filename, recordId }).then(result=>{
this.fileData = null
let title = `${filename} uploaded successfully!!`
this.toast(title)
})
}

toast(title){
const toastEvent = new ShowToastEvent({
title,
variant:"success"
})
this.dispatchEvent(toastEvent)
}
}

CSS
NIL

APEX Class:
public with sharing class AccountController{
@AuraEnabled
public static String uploadFile(String base64, String filename, String recordId) {
ContentVersion cv = createContentVersion(base64, filename);
ContentDocumentLink cdl = createContentLink(cv.Id, recordId);
if (cv == null || cdl == null) { return null; }
return cdl.Id;
}

private static ContentVersion createContentVersion(String base64, String filename) {

Page 118
ContentVersion cv = new ContentVersion();
cv.VersionData = EncodingUtil.base64Decode(base64);
cv.Title = filename;
cv.PathOnClient = filename;
try {
insert cv;
return cv;
} catch(DMLException e) {
System.debug(e);
return null;
}
}

private static ContentDocumentLink createContentLink(String contentVersionId, String


recordId) {
if (contentVersionId == null || recordId == null) { return null; }
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = [
SELECT ContentDocumentId
FROM ContentVersion
WHERE Id =: contentVersionId
].ContentDocumentId;
cdl.LinkedEntityId = recordId;
cdl.ShareType = 'V';
try {
insert cdl;
return cdl;
} catch(DMLException e) {
System.debug(e);
return null;
}
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>

Page 119
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 120
Scenario 35:
Use of Screen Flow in LWC - Create Two Screen Flow (Account & Contact Creation) Use
them in LWC.

Pre-Steps:
1. Create two Screen flows one for Contact and one for Account.
2. Also create two text variable in each flow named as “recordId” and “ObjectName”
3. recordId variable is used in the Create record block to store newly created record.
4. ObjectName variable is used to pass the object name to open the flow.

Page 121
Page 122
HTML
<template>
<lightning-card title="Quick Record Create" icon-
name="custom:custom1">
<lightning-tabset variant="vertical">
<template for:each={sObjectToFlowMap} for:item="obj">
<lightning-tab
label={obj.sObject}
key={obj.sObject}
value={obj.sObject}
onactive={handleTabActive}
>
<lightning-flow
flow-api-name={obj.flowName}
onstatuschange={handleAccountStatusChange}
flow-input-variables={inputVariables}
>
</lightning-flow>
</lightning-tab>
</template>
</lightning-tabset>

Page 123
</lightning-card>
</template>

JS
import { LightningElement, track } from "lwc";
import { NavigationMixin } from "lightning/navigation";

export default class QuickRecordCreate extends


NavigationMixin(LightningElement) {
sObjectToFlowMap;
@track inputVariables = [];

connectedCallback() {
this.sObjectToFlowMap = [
{
sObject: "Account",
flowName: "Create_account"
},
{
sObject: "Contact",
flowName: "create_Contact"
},

];
}

handleTabActive(event) {
this.inputVariables = [
{
name: "ObjectName",
type: "String",
value: event.target.value
}
];
}

handleAccountStatusChange(event) {
if (event.detail.status === "FINISHED") {

Page 124
let recordId;
let objectApiName;
const outputVariables = event.detail.outputVariables;
for (let i = 0; i < outputVariables.length; i++) {
const outputVar = outputVariables[i];
if (outputVar.name === "recordId") {
recordId = outputVar.value;
}
if (outputVar.name === "ObjectName") {
objectApiName = outputVar.value;
}
}
this[NavigationMixin.Navigate]({
type: "standard__recordPage",
attributes: {
recordId: recordId,
objectApiName: objectApiName,
actionName: "view"
}
});
}
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Page 125
Output Screenshot

Page 126
Scenario 36:
LMS Complex Example

Pre-Steps:
1. Create a folder named ‘messageChannels’ at
force-app/main/default location
2. After the folder is established, the next step involves creating
the initial Lightning message channel XML file, which should
have the “.messageChannel-meta.xml” suffix.
3. And paste this XML in above File.

Selected_EntityId.messageChannel-meta.xml
<?xml version="1.0" encoding="UTF-8" ?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>SelectedEntityId</masterLabel>
<isExposed>true</isExposed>
<description>Message Channel to pass a entity Id</description>

Page 127
<lightningMessageFields>
<fieldName>entityInfo</fieldName>
<description>This is the record information that
selected</description>
</lightningMessageFields>
</LightningMessageChannel>

sendData.HTML
<template>
<lightning-card title="Lightning Message Service: communication
between LWC Components"
icon-name="custom:custom30">
<div >
<lightning-layout>
<lightning-layout-item padding="around-small">
<template if:true={accounts.data}>
<template for:each={accounts.data} for:item="account">
<div class="custom-box slds-box slds-var-p-around_medium slds-
text-align_center"
key={account.Id} data-item={account.Id} onclick={handleClick}>
<div class="slds-text-heading_small">{account.Name}</div>
</div>
</template>
</template>
</lightning-layout-item>
</lightning-layout>
</div>
</lightning-card>
</template>

sendData.JS
import { LightningElement, wire} from 'lwc';
import getAccountLocations from
'@salesforce/apex/AccountController.getAccountLocations';
// Import message service features required for publishing and the message
channel

Page 128
import { publish, MessageContext } from 'lightning/messageService';
import selectedEntity from
'@salesforce/messageChannel/Selected_EntityId__c';

export default class ShowAccountList extends LightningElement {

@wire(MessageContext)
messageContext;

//retrieve account records from database via Apex class


@wire(getAccountLocations) accounts;
//clicking the div fires this event
handleClick(event) {
//retrieve AccountId from div
let accountId = event.currentTarget.dataset.item;
let arr = this.accounts.data.find(element => element.Id ==
accountId);
let payload = { record: arr };
publish(this.messageContext, selectedEntity, payload);
}
}

sendData.CSS
.c-container {
border: 1px solid #d8dde6;
margin: 10px 0 20px;
}
.custom-box {
background-color: #f4f6f9;
}

sendData.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>

Page 129
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

reciver.HTML
<template>
<lightning-card title="Lightning Map component will show selected
Company Location"
icon-name="custom:custom30">
<template if:true={isDisplayLocation}>
<div class="slds-text-heading_small">{selectedAccountName}</div>
<lightning-map
map-markers={mapMarkers}
markers-title={selectedAccountName}
zoom-level = {zoomLevel}
center = {center}>
</lightning-map>
</template>
</lightning-card>
</template>

import { LightningElement, wire, track} from 'lwc';


// Import message service features required for subscribing and the
message channel
import {subscribe,unsubscribe,APPLICATION_SCOPE,MessageContext} from
'lightning/messageService';
import selectedEntity from
'@salesforce/messageChannel/Selected_EntityId__c';

let acct;
export default class DisplayLocationSubscriber extends LightningElement {
subscription = null;
record;

isDisplayLocation=false;
@track mapMarkers = []; //holds account location related attributes
markersTitle = ''; //title of markers used in lightning map.

Page 130
zoomLevel = 4; //initialize zoom level
center; //location will be displayed in the center of the map

selectedAccountName = '';

@wire(MessageContext)
messageContext;

// Standard lifecycle hooks used to subscribe and unsubsubscribe to


the message channel
connectedCallback() {
this.subscribeToMessageChannel();
this.isDisplayLocation = false;
}

disconnectedCallback() {
this.unsubscribeToMessageChannel();
}

// Encapsulate logic for Lightning message service subscribe and


unsubsubscribe
subscribeToMessageChannel() {
if (!this.subscription) {
this.subscription = subscribe(
this.messageContext,
selectedEntity,
(message) => this.handleMessage(message),
{ scope: APPLICATION_SCOPE }
);
}
}

unsubscribeToMessageChannel() {
unsubscribe(this.subscription);
this.subscription = null;
}

// Handler for message received by component


handleMessage(message) {
//assigns account records

Page 131
acct = message.record;

this.selectedAccountName = acct.Name;

//prepares information for the lightning map attribute values.


this.markersTitle = acct.Name;

this.mapMarkers = [
{
location: {
Street: acct.BillingStreet,
City: acct.BillingCity,
State: acct.BillingState,
Country: acct.BillingCountry,
},
icon: 'custom:custom26',
title: acct.Name,
}
];
this.center = {
location: {
City: acct.BillingCity,
},
};
this.zoomLevel = 6;
this.isDisplayLocation = true;
}
}

CSS
NIL

reciver.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>

Page 132
</targets>
</LightningComponentBundle>

Output Screenshot

Page 133
Reference Doc: https://santanuboral.blogspot.com/2021/02/lms-with-lwc.html

Scenario 37:
Use of LWC in Aura Component

lwctoAura.HTML
<template>
<div class="slds-box">
<div if:true={DisplayText}>{textValue}</div>
</div>
</template>

lwctoAura.JS
import { LightningElement, track, api } from 'lwc';
export default class lWCComponent extends LightningElement
{
DisplayText = false;
textValue='LWC Function Invoked through Aura Component'
@api LWCFunction()
{
this.DisplayText = true;
}
}

Page 134
lwctoAura.CSS
NIL

lwctoAura.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

POST steps :
1. Deploy above Component.
2. Go to Developer Console>File>New> Lightning Component.(create aura Comp)
3. Paste below code

newcomp.cmp
<aura:component
implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableF
orRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
<div class="slds-box">
<lightning:button variant="brand" label="Call LWC Function" onclick="{!
c.handleClick }" />
</div>
<c:lwctoAura aura:id="lWCComponent2"></c:lwctoAura>
</aura:component>

newcmpController.js
({
handleClick : function(component, event, helper)
{
component.find('lWCComponent2').LWCFunction ();
}

Page 135
})

4. Go to Object Manager > Contact> Button link action> new Action >
5. Choose Action Type : Lightning Component.
6. Choose the above Aura cmp.
7. Give Appropriate Label.
8. Now make available this action in Page layout.

Output Screenshot

Scenario 38:

Page 136
Pass Data From Lightning Web Component to Screen Flow and Latitude and Longitude
Values are auto populated from LWC

HTML
<template>
<lightning-input-location label="Default coordinates"
latitude={latitude} longitude={longitude} onchange={handleChange}>
</lightning-input-location>
</template>

JS
import { LightningElement, api } from 'lwc';
import {FlowAttributeChangeEvent} from 'lightning/flowSupport';

export default class LwcToScreenFlow extends LightningElement {


@api latitude;
@api longitude;

handleChange(event){
this.latitude = event.target.latitude;
this.longitude = event.target.longitude;

["latitude", "longitude"].forEach((loc) =>


this.dispatchEvent(new FlowAttributeChangeEvent(loc,
this[loc]))
);
}
}

CSS
NIL

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

Page 137
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__FlowScreen</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__FlowScreen">
<property label="Latitude" name="latitude" type="Integer"
role="outputOnly"/>
<property label="Longitude" name="longitude" type="Integer"
role="outputOnly"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

POST steps :
1. Create a Screen Flow .
2. On Flow Designer, click on the +icon and select the Screen element.
3. Input the following information:
a. Enter the Label of your choice the API Name will auto-
populate.
4. Under the Input section on Screen Element, drag and drop the
Number component onto the screen.
5. Input the following information:
a. Enter Label the API Name will auto-populate.
b. Default Value: {!lwcToFlow.latitude}
6. Under the Input section on Screen Element, drag and drop the
Number component onto the screen.
7. Input the following information:
a. Enter Label the API Name will auto-populate.
b. Default Value: {!lwcToFlow.longitude}
8. Click Save.
9. Enter Flow Label the API Name will auto-populate.
10. Click Show Advanced.
11. API Version for Running the Flow: 58
12. Interview Label: Pass from Screen Flow to LWC {!
$Flow.CurrentDateTime}
13. Click Save.

Output Screenshot

Page 138
Scenario 39:
Parent to Child data display using Events - Show Accounts in a data table, if any account
is selected then show its data on right panel.

Parent.HTML
<template>
<lightning-card title="Account List">
<lightning-datatable
key-field="Id"
data={accounts}
columns={columns}
onrowselection={handleRowSelection}>
</lightning-datatable>
</lightning-card>
<c-account-details-child selected-account={selectedAccount}></c-
account-details-child>
</template>

Parent.JS

Page 139
import { LightningElement, wire } from 'lwc';
import getparentAccounts from
'@salesforce/apex/AccountController.getparentAccounts';

export default class AccountListParent extends LightningElement {


accounts;
selectedAccount;

columns = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Industry', fieldName: 'Industry', type: 'text' },
{ label: 'Annual Revenue', fieldName: 'AnnualRevenue', type:
'currency' }
];

@wire(getparentAccounts)
wiredAccounts({ error, data }) {
if (data) {
this.accounts = data;
} else if (error) {
console.error(error);
}
}

handleRowSelection(event) {
const selectedRows = event.detail.selectedRows;
this.selectedAccount = selectedRows.length ? selectedRows[0] :
null;
}
}

CSS
NIL

Parent.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>

Page 140
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

accountDetailChild.HTML
<template>
<lightning-card title="Account Details" if:true={selectedAccount}>
<div class="slds-p-around_small">
<p><b>Name:</b> {selectedAccount.Name}</p>
<p><b>Industry:</b> {selectedAccount.Industry}</p>
<p><b>Annual Revenue:</b> {selectedAccount.AnnualRevenue}</p>
</div>
</lightning-card>
</template>

accountDetailChild.JS
import { LightningElement, api } from 'lwc';

export default class AccountDetailsChild extends LightningElement {


@api selectedAccount;
}

CSS
NIL

reciver.XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Output Screenshot

Page 141
Scenario 40:
Fetch account with contacts through apex and display in two different data tables.
HTML
<template>
<lightning-card title="Accounts" icon-name="standard:account">
<lightning-datatable
key-field="Id"
data={accounts}
columns={accountColumns}>
</lightning-datatable>
</lightning-card>
<lightning-card title="Contacts" icon-name="standard:contact">

Page 142
<lightning-datatable
key-field="Id"
data={contacts}
columns={contactColumns}>
</lightning-datatable>
</lightning-card>
</template>

JS
import { LightningElement, wire } from 'lwc';
import getAccountsandContactsData from
'@salesforce/apex/AccountController.getAccountsandContactsData';

export default class AccountContactDisplay extends LightningElement {


accounts;
contacts;
accountColumns = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Industry', fieldName: 'Industry', type: 'text' },
{ label: 'Annual Revenue', fieldName: 'AnnualRevenue', type:
'currency' }
];
contactColumns = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'text' }

];

@wire(getAccountsandContactsData)
wiredAccounts({ error, data }) {
if (data) {
// Separate accounts and contacts from the response
this.accounts = data.map(account => ({
Id: account.Id,
Name: account.Name,
Industry: account.Industry,
AnnualRevenue: account.AnnualRevenue
}));

Page 143
this.contacts = data.flatMap(account => account.Contacts);
} else if (error) {
// Handle error
}
}
}

CSS
NIL

APEX Class:
public with sharing class AccountController{
@AuraEnabled(cacheable=true)
public static List<Account> getAccountsandContactsData() {
List<Account> accountsWithContacts= [SELECT Id, Name, Industry,AnnualRevenue,
(SELECT Id, Name, Email FROM Contacts) FROM Account LIMIT 10];
system.debug(accountsWithContacts);
return accountsWithContacts;
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Output Screenshot

Page 144
Page 145
Scenario 41:
Create a LWC to show Contact records in dataTable also having extra features like- Next ,
previous , First , Last Pages , also show total records also we can set the how much
record to display using Pagination.

HTML
<template>
<template if:true={records}>
<!--LIGHTNING DATATABLE-->
<div style="height:400px">
<lightning-datatable key-field="Id" data={recordsToDisplay}
hide-checkbox-column="true" columns={columns}></lightning-datatable>
</div>
<div class="slds-grid slds-grid_vertical-align-center slds-
grid_align-spread" style="padding-top: 0.5em;">
<!--RECORDS PER PAGE-->
<div class="slds-col">
<div class="slds-list_inline slds-p-bottom_xx-small">
<label class="slds-text-color_weak slds-p-
horizontal_x-small" for="recordsPerPage">Page Size:</label>
<div class="slds-select_container">

Page 146
<select class="slds-select" id="recordsPerPage"
onchange={handleRecordsPerPage}>
<template for:each={pageSizeOptions}
for:item="option">
<option key={option}
value={option}>{option}</option>
</template>
</select>
</div>
</div>
</div>
<!--PAGE NAVIGATION-->
<div class="slds-align_absolute-center" style="height:5rem">
<lightning-button disabled={bDisableFirst} icon-
name="utility:jump_to_left" label="First" class="slds-p-horizontal_x-
small" alternative-text="first page" onclick={firstPage}></lightning-
button>
<lightning-button disabled={bDisableFirst} icon-
name="utility:chevronleft" label="Previous" alternative-text="Previous"
onclick={previousPage}></lightning-button>
&nbsp;
<span class="slds-badge">Showing {pageNumber}
&nbsp;of&nbsp; {totalPages} &nbsp;&nbsp;Page(s)</span>
&nbsp;
<lightning-button disabled={bDisableLast} icon-
name="utility:chevronright" label="Next" alternative-text="Next"
onclick={nextPage} class="slds-p-horizontal_x-small" icon-
position="right"></lightning-button>
<lightning-button disabled={bDisableLast} icon-
name="utility:jump_to_right" label="Last" alternative-text="last page"
onclick={lastPage} icon-position="right"></lightning-button>
</div>
<!--TOTAL RECORDS-->
<div class="slds-clearfix">
<div class="slds-float_right">
<span class="slds-badge"> Total Records:
{totalRecords}</span>
</div>
</div>
</div>

Page 147
</template>
</template>

JS
import {LightningElement} from 'lwc';
//Import apex method
import FetchConRec from '@salesforce/apex/AccountController.FetchConRec';
export default class DatatableWithPagination extends LightningElement {

// JS Properties
pageSizeOptions = [5, 10, 25, 50, 75, 100]; //Page size options
records = []; //All records available in the data table
columns = []; //columns information available in the data table
totalRecords = 0; //Total no.of records
pageSize; //No.of records to be displayed per page
totalPages; //Total no.of pages
pageNumber = 1; //Page number
recordsToDisplay = []; //Records to be displayed on the page

get bDisableFirst() {
return this.pageNumber == 1;
}
get bDisableLast() {
return this.pageNumber == this.totalPages;
}
// connectedCallback method called when the element is inserted into a
document
connectedCallback() {
// set datatable columns info
this.columns = [{
label: 'Name',
fieldName: 'Name'
},
{
label: 'Email',
fieldName: 'Email'
},
{
label: 'Phone',

Page 148
fieldName: 'Phone'
},
{
label: 'Title',
fieldName: 'Title'
},
];
// fetch contact records from apex method
FetchConRec()
.then((result) => {
if (result != null) {
console.log('RESULT--> ' + JSON.stringify(result));
this.records = result;
this.totalRecords = result.length; // update total
records count
this.pageSize = this.pageSizeOptions[0]; //set
pageSize with default value as first option
this.paginationHelper(); // call helper menthod to
update pagination logic
}
})
.catch((error) => {
console.log('error while fetch contacts--> ' +
JSON.stringify(error));
});
}
handleRecordsPerPage(event) {
this.pageSize = event.target.value;
this.paginationHelper();
}
previousPage() {
this.pageNumber = this.pageNumber - 1;
this.paginationHelper();
}
nextPage() {
this.pageNumber = this.pageNumber + 1;
this.paginationHelper();
}
firstPage() {
this.pageNumber = 1;

Page 149
this.paginationHelper();
}
lastPage() {
this.pageNumber = this.totalPages;
this.paginationHelper();
}
// JS function to handel pagination logic
paginationHelper() {
this.recordsToDisplay = [];
// calculate total pages
this.totalPages = Math.ceil(this.totalRecords / this.pageSize);
// set page number
if (this.pageNumber <= 1) {
this.pageNumber = 1;
} else if (this.pageNumber >= this.totalPages) {
this.pageNumber = this.totalPages;
}
// set records to display on current page
for (let i = (this.pageNumber - 1) * this.pageSize; i <
this.pageNumber * this.pageSize; i++) {
if (i === this.totalRecords) {
break;
}
this.recordsToDisplay.push(this.records[i]);
}
}
}

APEX Class:
public with sharing class CreateRecord {
@AuraEnabled (cacheable=true)
public static List<Contact> FetchConRec(){
return[SELECT id,name,email,phone,title FROM Contact LIMIT 5000];
}

Page 150
XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Reference Doc:

https://lwcfactory.com/pagination-with-datatable-in-salesforce-lwc/

Output Screenshot

Page 151
Scenario 42:
Create A LWC to use Lazy Loading Pagination

HTML
<template>
<div style="height:500px">
<!-- Infinite scrolling enables you to load a subset of data and then
display more when users scroll to the end of the table -->

<lightning-datatable key-field="Id"
data={accounts}
columns={columns}
enable-infinite-loading
onloadmore={loadMoreDataHandler}
hide-checkbox-column="true"
show-row-number-column="true">
</lightning-datatable>
</div>
</template>

JS
import { LightningElement, track, wire } from 'lwc';
import AccountRecords from
'@salesforce/apex/AccountController.AccountRecords';

Page 152
const columns = [
{ label: 'Id', fieldName: 'Id', type: 'text' },
{ label: 'Name', fieldName: 'Name', type: 'text'},
{ label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'text'}

];

export default class LazyLoadingLWC extends LightningElement {


accounts=[];
error;
columns = columns;
rowLimit =20;
rowOffSet=0;

connectedCallback() {
this.loadData();
}

loadData(){
return AccountRecords({ limitSize: this.rowLimit , offset :
this.rowOffSet })
.then(result => {
//Updating the accounts array from result as well apart from
updating the updatedRecords variable
let updatedRecords = [...this.accounts, ...result];
this.accounts = updatedRecords;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.accounts = undefined;
});
}

loadMoreDataHandler(event) {
const currentRecord = this.accounts;
const { target } = event;
target.isLoading = true;

this.rowOffSet = this.rowOffSet + this.rowLimit;

Page 153
this.loadData()
.then(()=> {
target.isLoading = false;
});
}
}

APEX Class:
public with sharing class CreateRecord {
@AuraEnabled(cacheable=true)
public static List<Account> AccountRecords(Integer limitSize, Integer offset){
List<Account> accountListRec = [SELECT Id,Name, AnnualRevenue
FROM Account
ORDER BY CreatedDate
LIMIT :limitSize
OFFSET :offset
];
return accountListRec;
}

XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Reference Doc:

Page 154
https://www.apexhours.com/lazy-loading-in-lightning-web-component/

Output Screenshot

Page 155

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy