Tuesday, 26 December 2023
getPicklistValuesByRecordType Adaptor
Wednesday, 20 December 2023
LWC getPicklistValues
getPicklistValues
Use this wire adapter to get the picklist values for a specified field.
Syntax
import {lightningElement } from 'lwc';
import {getPicklistValues} from 'lightning/uiObjectInfoApi';
import STATUS_Field from '@salesforce/schema/Account.status';
export default class Example LightningEvent{
@wire(getPicklistValues,{recordTypeId: '021XXXXXXXXXXXXX',fieldApiName:STATUS_Field})
propertyorfunction
}
Tuesday, 19 December 2023
LWC getObjectInfo adapter
Example 1
getObjectInfoadapter js
import { LightningElement,track } from 'lwc';
import {getObjectInfoApi} from 'lightning/uiObjectInfoApi';
import Contact_OBJECT from '@salesforce/schema/Contact';
export default class AccountDisplatRecords extends LightningElement {
defaultRecordTypeId
@wire(getObjectInfoApi, {objectApiName:Contact_OBJECT})
objectInfo({data,error}){
if(data){
// check Inspect all the atribute we get it
this.defaultRecordTypeId = data.defaultRecordTypeId
}if(error){
console.error(error)
}
}
}
getObjectInfoadapter html
<tempalte>
<lightning-card title = "getObjectInfo Adapter">
<div class="slds-var-p-around_medium">
{defaultRecordTypeId}
</div>
</lightning-card>
</tempalte>
Another Example 2
getObjectInfoadapter js
import { LightningElement,track } from 'lwc';
import {getObjectInfoApi} from 'lightning/uiObjectInfoApi';
import Contact_OBJECT from '@salesforce/schema/Contact';
export default class AccountDisplatRecords extends LightningElement {
defaultRecordTypeId
@wire(getObjectInfoApi, {objectApiName:Contact_OBJECT})
objectInfo
}
getObjectInfoadapter html
<tempalte>
<lightning-card title = "getObjectInfo Adapter">
<div class="slds-var-p-around_medium">
defaultRecordTypeId: {objectInfo.data.defaultRecordTypeId}
defaultapiName: {objectInfo.data.apiName}
</div>
</lightning-card>
</tempalte>
getObjectInfos
Use this wire adapter to get metadata for multiple objects. The response includes metadata describing
the fields, child relationships, record type, and theme for each objects
Syntax
import {LightningElement, wire} from 'lwc';
import {getObjectInfos} from 'lightning/uiObjectInfoApi';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
export default class GetObjectInfosExample extends LightningElement{
objectapirecords = [ACCOUNT_OBJECT,CONTACT_OBJECT];
@wire(getObjectInfos,{objectApiNames : $objectapirecords})
propertyorFunction
}
Parent to Child Passing Data Use @wire
Parent to Child Passing Data Value
public class DisplayAccountRecordsget{
public static list<contact> getAccountRecords(){
return [select id,lastname,firstname,phone from contact limit 10];
}
}
parenttochildpassdata js
-----------------------------
import {LightningElement} from 'lwc';
import getrecords from '@salesforce/apex/DisplayContactRecordsget.getContactRecords';
export default class parenttochildpassdata extends LightningElement {
datadisplayed
@wire(getrecords)
datawire({data,error})
if(data){
this.datadisplayed = data;
} else if(error){
console.log('Error feacting data from Apex:'+error);
}
parenttochidpassdata html
<template>
<lightning-card>
<c-childtoparentpassdata contacts = {datadisplayed}><c-childtoparentpassdata>
</lightning-card>
</template>
childtoparentpassdata js
import {lightningElement , api} from 'lwc';
export default class childtoparentpassdata extends LightningElement {
@api contacts
}
childtoparentpassdata html
<template>
<lightning-card variant="Narrow" title="Parent to Child" icon-name="standard:contact">
<template if:true={contacts}>
<template for:each={contacts} for:item = "conlist">
<li key={conlist.id}> Contact FirstName - {con.FirstName}
Contact LastName - {con.LastName}
Contact Phone - {con.Phone}</li>
</template>
</lightning-card>
</template>
Child To Parent Data Passing Value
Chtil to Parent Passing Data Apex
public class DisplayAccountRecords{
public static list<account> getAccountRecords(){
return [select id,name,phone from account];
}
}
Childaccountinsertrecord Js Component Name
import { LightningElement } from 'lwc';
import getrecords from '@salesforce/apex/DisplayRecords.getAccountRecords';
export default class ChildaccountinsertComponent extends LightningElement {
@wire(getrecords)
wirdata({data,error}){
if(data){
const childcomponentdata = new CustomEvent('dataready',{detail:data});
this.dispatchEvent(childcomponentdata);
} else if(error){
console.log('Error feacting data from Apex:'+error);
}
}
}
Childaccountinsertrecord Js Component Name
import { LightningElement } from 'lwc';
import getrecords from '@salesforce/apex/DisplayRecords.getdisplayedrecords';
export default class ChildaccountinsertComponent extends LightningElement {
@wire(getrecords)
wirdata({data,error}){
if(data){
const childcomponentdata = new CustomEvent('dataready',{detail:data});
this.dispatchEvent(childcomponentdata);
} else if(error){
console.log('Error feacting data from Apex:'+error);
}
}
}
childaccountinsertrecord html Component Name
<template>
<!- I can not displayed any data ->
</template>
Parentaccountinsertrecord Js Component Name
import { LightningElement } from 'lwc';
export default class ParentaccountinsertComponent extends LightningElement {
receivedData
handleDataReady(event){
this.receivedData = event.detail
}
}
Parentaccountinsertrecord html Component Name
<template>
<lightning-card title= "Parent Comonent">
<div>
<c-childaccountinsertrecord ondataready = {handleDataReady}></c-childaccountinsertrecord>
</div>
<template if:true={receivedData}>
<template for:each={receivedData} for:item={acc}>
<li> Account ID :- {acc.id} </li>
<li> Account Name :- {acc.Name} </li>
<li> Account Phone :- {acc.Phone} </li>
</template>
</lightning-card>
</template>
Rest API Callout Service Example
Rest API Callout Service Example
public class RestAPIDisplayValue {
@AuraEnabled(cacheable=true)
public static String getRestAPI(Integer id){
Http htp = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json');
req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
HttpResponse res = htp.send(req);
String strReq = '';
if(res.getStatusCode() == 200){
map<String,object> result = (Map<String,object>)JSON.deserializeUntyped(res.getBody());
map<String,object> animals = (Map<String,object>) result.get('animal');
strReq = String.valueOf(animals.get('name'));
System.debug('datadisplaid'+strReq);
}
return strReq;
}
}
RestAPI DisplayedRecords
----------------------------
import { LightningElement,track } from 'lwc';
import getrestapi from '@salesforce/apex/RestAPIDisplayValue.getRestAPI';
export default class RestAPIDetail extends LightningElement {
@track animalId;
@track animalName;
handleInputChange(event){
this.animalId = event.target.value
}
getRestapiDetail(){
getrestapi({
id: this.animalId
})
.then(result => {
console.log('result'+result);
this.animalName = result;
})
.catch(error,{
});
}
}
Displayed we get response
------------------------
<template>
<lightning-card variant="Narrow" title="Animal Locator" icon-name="utility:animal_and_nature">
<div>
<lightning-input label="Enter Animal ID" type="number" value={animalId} onchange={handleInputChange}></lightning-input>
<lightning-button variant="base" label="Get Animal Name" onclick={getRestapiDetail}></lightning-button>
<div if:true={animalName}>
<p>Animal Name: {animalName}</p>
</div>
</div>
</lightning-card>
</template>
Displayed Apex Get Data Use @wire
Apex Get Data
public class DisplayRecordWire {
@AuraEnabled(cacheable=true)
public static list<contact> Displayrecords(){
return [select id,lastname,firstname,phone from contact limit 10];
}
}
DisplayRecordWire.js
import { LightningElement,wire } from 'lwc';
import getcontactswire from '@salesforce/apex/DisplayRecordWire.Displayrecords';
export default class DisplayRecordsWire extends LightningElement {
wiredisplayed
@wire(getcontactswire)
contactrecord({data,error}){
if(data){
this.wiredisplayed = data
console.log('displayed records'+data)
} if(error){
console.error('displayrecordserror'+error)
}
}
}
DisplayRecordWire HTML
<template>
<lightning-card title="Contact Records" icon-name="standard:contact">
<div class="slds-m-around_medium">
<template if:true={wiredisplayed}>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<template for:each={wiredisplayed} for:item="contact">
<tr key={contact.Id}>
<td>{contact.LastName}</td>
<td>{contact.FirstName}</td>
<td>{contact.Phone}</td>
</tr>
</template>
</tbody>
</table>
</template>
<template if:true={error}>
<p>Error retrieving contact records: {error}</p>
</template>
</div>
</lightning-card>
</template>
Imparative to display records and CRED Operation
Account Records JS
import { LightningElement,track } from 'lwc';
import getaccounts from '@salesforce/apex/AccountDisplayRecord.getrecordsdisplay';
import createRecord from '@salesforce/apex/AccountDisplayRecord.CreateRecord';
export default class AccountDisplatRecords extends LightningElement {
@track acclist
@track newAccountName
@track newAccountPhone
@track newAccountEmail
connectedCallback() {
this.Displayrecords();
}
Displayrecords(){
getaccounts().then(result => {
this.acclist = result
}).catch(error => {
system.debug('Error no records displayed'+error);
});
}
handleNameChange(event){
this.newAccountName = event.target.value;
}
handlePhoneChange(event){
this.newAccountPhone = event.target.value;
}
handleEmailChange(event){
this.newAccountEmail = event.target.value;
}
handlerCreateRecord(){
//CreateRecords
createRecord({
name:this.newAccountName,
phone:this.newAccountPhone,
email:this.newAccountEmail
})
.then(result => {
return getaccounts();
})
.then(result => {
this.acclist = result;
})
.catch(error => {
console.log('error displayed records'+error)
});
}
}
Accountrecords Html
How to Import Reference to Salesforce Fields
How to Import Reference of Salesforce Standard Object
Syntax
Import objectName from '@salesforce/schema/Sobject'
Example
Import ACCOUNT_OBJECT from '@saleforce/schema/Account'
How to Import Reference to Salesforce Fields
Syntax
import FIELD_NAME from '@salesforce/schema/Sobject.fields'
Example
import ACCOUNT_NAME from '@salesforce/schema/ACCOUNT.NAME'
How to import Reference to a fields via a relationship
import REF_FIELD_NAME from '@salesforce/schema/object.relationship.fields'
What is @Wire Service?
What is @Wire Service?
1) Wire Service is build on Lightning Data Service
2) LWC component use @wire in their JavaScript class to read
data from one of the wire adapters in the lightning/ui*Api
3) @Wire is a reactive service.
4) The wire adapter defines the data shape that the wire service
provisions in an immutable stream
Syntax
import {adapterId} from 'adaptermodel'
@wire(adapterId, adapterconfig)
propertyorfuncation;
@wire service and feach user Details
import {lightningElement } from 'lwc';
import {getRecord} from 'lightning/ui';
import id from '@salesforce/user/id';
import NAME_FIELD from '@salesforce/schema/User.Name;
import EMAIL_FIELD from '@salesforce/schema/User.EMAIL;
const fields = [NAME_FIELD, EMAIL_FIELD];
export default class WireDemo extends LightningElement {
userId = id
@wire(getRecord,{recordId:'userId', fields:fields})
this is one way get data write it
Feach Data Value
----------------------------------------
userdetailHandler(response){
let data = response.data
let error = response.error
}
--------------------------------------
userDetail
// Function
userdetailHandler({data, error}){
if(data){
console.data(data)
this.userDetail = data.fields
}
if(error){
console.error(error)
}
}
@wire(getRecord,{recordId:'userId', fields:fields})
// Property
userdetailPropery;
}
LWC Different Between @wire and imperative
Lightning web components (LWC), @wire and imperative (or imperative Apex) are two approaches for interacting with Salesforce data and services.
@wire:
Use Case: Read-only Data Binding
1. When you want to automatically bind a property in your Lightning web component to a wire adapter's data.
2. When you need to retrieve data from Salesforce, such as records, fields, or metadata.
3. Suitable for scenarios where the data is mainly read-only, and you want to take advantage of LWC's automatic data binding.
Apex:
Public class accountretrievedata{
@AuraEnabled(cacheable=true)
Public static list<account> getaccorrecord(){
return [select id,name from account];
}
}
Js:AccountgetData
import {lightningElement } from 'lwc';
import getaccountrecord from '@salesforce/apex/accountretrievedata.getaccorrecord';
export default class WireExample extends LightningElement {
@wire(getaccountrecord)
accountdata
}
Imperative
Use Case: Dynamic Data Manipulation or Write Operations
1. When you need to perform dynamic data manipulation or executive write operations
like creating,updating, or deleting records
2. Suitable for scenarious where you need more control over when and how data is
fetched or updated
3. Can be used you want to handle errors explicity or need to perform custom logic
before or after making a server call.
Apex:-
Public class accountretrievedata{
@AuraEnabled
Public static list<account> getaccorrecord(){
return [select id,name from account];
}
}
Js: AccountgetData
import {LightningElement } from 'lwc';
import fetchData from '@salesforce/apex/accountretrievedata.getaccorrecord';
export default class WireExample extends LightningElement {
fetchDataFromServer(){
fetchData().then(result => {
})
.catch(error =>{
});
}
}
Calling child method from parent
Callingchildmethodfromparent Html
<template>
<lightning-button variant="base" label="Reset Silder" onclick={handleClick}></lightning-button>
<div class="slds-var-m-bottom_medium">
<c-parenttochildslidercomponent></c-parenttochildslidercomponent>
</div>
</template>
Callingchildmethodfromparent JS
import { LightningElement,api } from 'lwc';
export default class Parenttochild extends LightningElement {
handleClick(){
this.template.querySelector('c-parenttochildslidercomponent').resetslider()
}
}
-------------------------------------------------------------------------------------------------------------------
Parenttochildslidercomponent html
<template>
<lightning-card title="Calling child method from parent" >
<div class="slds-var-m-around_medium">
<lightning-slider label="Volume" value={val} onkeyup={changeHandler}></lightning-slider>
</div>
</lightning-card>
</template>
Parenttochildslidercomponent Js
import { LightningElement,api } from 'lwc';
export default class Parenttochildslidercomponent extends LightningElement {
val = 20
changeHandler(event){
this.val = event.target.value
}
@api resetslider(){
this.val = 30
}
}
Parent to Child Communication on action
Parent to Child Communication on action ParenttoChildCommunicationonaction Html <div class="slds-var-m-bottom_medium"></div> <lightning-card title="Parent to Child Communication on action" > <div class="slds-var-m-bottom_medium"> <lightning-input type="number" label="Enter Percentage"
onkeyup={handlerinputvalue}></lightning-input>
<c-parenttochild-progress-component progressvalue = {percentage} ></c-parenttochild-progress-component> </div> --------------------------------------------------- ParenttoChildCommunicationonaction JS import { LightningElement,api } from 'lwc'; export default class Parenttochild extends LightningElement { percentage = 10; handlerinputvalue(event){ this.percentage = event.target.value; } } --------------------------------------------------------------- ParenttoChildProgressComponent Html <template>
<lightning-progress-bar value={progressvalue} size="large">
</lightning-progress-bar> </template> ------------------------------------------------------------------- ParenttoChildProgressComponent JS import { LightningElement,api } from 'lwc'; export default class ParenttochildProgressComponent extends
LightningElement { @api progressvalue }
Parent to Child Non-Primitive Data Communication
ParentToChild Non-Primitive Data <template> <div class="slds-var-m-bottom_medium"> <c-parenttochild-carouse-component carousel-detail = {carouselData} ></c-parenttochild-carouse-component> </div> </template> ----------------------------------------------- Parenttochild JS import { LightningElement,api } from 'lwc'; export default class Parenttochild extends LightningElement { carouselData = [ { src : "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-01.jpg", header : "First Card", description : "First card description." }, { src : "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-02.jpg", header : "Secound Card", description : "Secound card description." }, { src : "https://www.lightningdesignsystem.com/assets/images/carousel/carousel-03.jpg", header : "Third Card", description : "Third card description." }] } --------------------------------------------- ParenttochildCarouseComponent <template> <lightning-card title="Parent to Child non-primitive data communication" > <div class="slds-var-m-around_medium"> <lightning-carousel> <template for:each={carouselDetail} for:item="carousel"> <lightning-carousel-image key = {carousel.header} src = {carousel.src} header = {carousel.header} description = {carousel.description} > </lightning-carousel-image> </template> </lightning-carousel> </div> </lightning-card> </template> ----------------------------------------------------------------- ParenttochildCarouseComponent JS import { LightningElement,api } from 'lwc'; export default class ParenttochildCarouseComponent extends LightningElement { @api carouselDetail }
LWC Parent to Child Primitive Data Communication
<template>
<c-parenttochildalertcomponent
message = "I got the data"
card-heading = "Parent to Child primitive data communication"
number = 20
is-valid >
</c-parenttochildalertcomponent>
</template>
-------------------------------------------------------
parenttochildalertcomponent
<template>
<lightning-card variant="Narrow" icon-name="standard:account">
<div>
{message}
{cardHeading}
{number}
{isValid}
</div>
</lightning-card>
</template>
import { LightningElement,api } from 'lwc';
export default class Parenttochildalertcomponent extends LightningElement {
@api message
@api cardHeading
@api number
@api isValid
}
Child To Parentcomponent
Custom Event Passing data
ChildtoParentcomponent Html
-----------------------
<template>
<lightning-card title="Child to parent communication">
<div class="slds-var-m-around_medium" onclose = {closeHandler}>
<lightning-button variant="base" label="Show Model" onclick={clickHandler}></lightning-button>
<template if:true={Showmodel}>
<c-childto-parent-model-component ></c-childto-parent-model-component>
</template>
<h1>{msg}</h1>
</div>
</lightning-card>
</template>
javaScript
----------
import { LightningElement } from 'lwc';
export default class ChildtoParentComponentEvent extends LightningElement {
Showmodel = false
msg
clickHandler(){
this.Showmodel = true
}
closeHandler(event){
this.msg = event.detail.msg
this.Showmodel = false
}
}
childtoparentcomponentmodel html
<template>
<lightning-card title="Hello">
<section role="dialog" tabindex="-1" aria-modal="true"
aria-labelledby="modal-heading-01"
class="slds-modal slds-fade-in-open slds-modal_small">
<div class="slds-modal__container">
<div class="slds-modal__header">
<h1 id="modal-heading-01"
class="slds-modal__title slds-hyphenate">Confirmation</h1>
</div>
<div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
<p>Successfully Created!!</p>
</div>
<div class="slds-modal__footer" onclick={footerHandler}>
<button class="slds-button slds-button_neutral"
onclick={CloseHandler}>OK</button>
</div>
</div>
</section>
<div class="slds-backdrop slds-backdrop_open" role="presentation"></div>
</lightning-card>
</template>
ChildtoParentModelComponent javaScript
------------
import { LightningElement } from 'lwc';
export default class ChildtoParentModelComponent extends LightningElement {
CloseHandler(){
const myEvent= new CustomEvent('close',{
bubbles:true,
detail: {
msg: 'Model Closed Successfully!!'
}
})
this.dispatchEvent(myEvent)
}
footerHandler(){
console.log('Footer Handler Event');
}
}
SetMethodParent Component
SetMethodParent Component Html
<template>
<lightning-card variant="Narrow" title="Setter Method Demo" >
<c-set-method-child detail = {userDetails}></c-set-method-child>
</lightning-card>
</template>
SetMethodParent Componentjs
import { LightningElement } from 'lwc';
export default class SetMethod extends LightningElement {
<-- user Details age multiple *2 use write code child component call to
parent update age-->
userDetails = {
name:"salesforcetroop",
age:25
}
}
setMethodChild Component Html
<template>
<lightning-card variant="Narrow" title="Hello" icon-name="standard:account">
<p class="slds-p-horizontal_small"><strong>Name -{detail.name} </strong></p>
<p class="slds-p-horizontal_small"><strong>Name -{detail.age} </strong></p>
</lightning-card>
</template>
setMethodChild Component Js
import { LightningElement,api } from 'lwc';
export default class SetMethodChild extends LightningElement {
userDetail
@api
get detail(){
return this.userDetail
}
set detail(data){
let newAge = data.age*2
this.userDetail = {...data, age:newAge}
}
}
L M S Passing Data Two UnRealted Component
Step :- 1) Create A New Folder Add the MessageChannel
Step :- 2) Create lightningMessageChannel add Fields
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>messageChannels</masterLabel>
<isExposed>true</isExposed>
<description>Message Channel to pass data</description>
<lightningMessageFields>
<fieldName>lmsData</fieldName>
<description>This is field to pass data</description>
</lightningMessageFields>
</LightningMessageChannel>
Step :- 3) update the manifest/package.xml file adding the lightningmessagechannel
<types>
<members>*</members>
<name>LightningMessageChannel</name>
</types>
version above 46 version
<version>58.0</version>
lightning Web Component Create lmscompanent A(LWS) HTML
<template>
<lightning-card title="LWC LMS Component One" >
<div class="slds-m-around_medium">
<lightning-input type="text" label="Enter message to publish"
onkeyup={inputHandler}>
</lightning-input>
</div>
<div class="slds-m-around_medium">
<lightning-button variant="base" label="publish" onclick={publishMessage} >
</lightning-button>
</div>
</lightning-card>
</template>
lightning Web Component Create lmscompanent A(LWS) JS
import { LightningElement,wire } from 'lwc';
import SAMPLEMC from '@salesforce/messageChannel/messageChannels__c';
import {MessageContext, publish} from 'lightning/messageService'
export default class LmsComponentA extends LightningElement {
inputValue
@wire(MessageContext)
context
inputHandler(event){
this.inputValue = event.target.value
}
publishMessage(){
const message={
lmsData:{
value:this.inputValue
}
}
//publish(messageContext, messageChannel, message)
publish(this.context, SAMPLEMC, message)
}
}
lightning Web Component Create lmscompanent X(LWS) HTML
<template>
<lightning-card title="LWC LMS Component X">
<div class="slds-m-around_medium">
<lightning-button label="unsubscribe"
onclick={unsubscribeMessage}></lightning-button>
</div>
<div class="slds-m-around_medium">
Message Recieved <strong>{recievedMessage}</strong>
</div>
</lightning-card>
</template>
lightning Web Component Create lmscompanent X(LWS) JS
import { LightningElement,wire } from 'lwc';
import SAMPLEMC from '@salesforce/messageChannel/messageChannels__c';
import {subscribe, MessageContext, APPLICATION_SCOPE, unsubscribe}
from 'lightning/messageService';
export default class LmsComponentX extends LightningElement {
recievedMessage
subscription
@wire(MessageContext)
context
connectedCallback(){
this.subscribeMessage()
}
subscribeMessage(){
//subscribe(messageContext, messageChannel, listener, subscriberOptions)
this.subscription= subscribe(this.context, SAMPLEMC,
(message)=>{this.handleMessage(message)}, {scope:APPLICATION_SCOPE})
}
handleMessage(message){
this.recievedMessage = message.lmsData.value?
message.lmsData.value :'NO Message published'
}
unsubscribeMessage(){
unsubscribe(this.subscription)
this.subscription = null
}
}