Wednesday 8 February 2023

                 Lazy Data Loading 

  •  Lazy loading helps with loading only the necessary piece and delaying the loading of the remaining until the user needs it, as opposed to bulk loading, which loads all of the data and renders it to the user at once.
  • Attributes:
    • Using the enable-infinite-loading option, you can load a portion of the data and then display more as viewers scroll to the table's finish. To retrieve extra data, use the onloadmore event handler.
    • load-more-offset: Calculates the number of pixels the table's scroll position is from the bottom of the table to determine when to start infinite loading. 20 is the default.
  • Visit Salesforce Document Link to understand more about Lightning data Table    https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation
Implementing Lazy Data Load for contact

public with sharing class LazyLoadingController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContact(Integer limitSize, Integer offset){
        List<Contact> contactList = [SELECT Id,Name
                                     FROM Contact
                                     ORDER BY CreatedDate
                                     LIMIT :limitSize
                                     OFFSET :offset
                                     ];
        return contactList;
    }
}

lazyLoadingLWCDemo

<template>
    <div style="height:500px">
    <lightning-datatable key-field="Id"
            data={contacts}
            columns={columns}
            enable-infinite-loading
            onloadmore={loadMoreData}
            hide-checkbox-column="true"
            show-row-number-column="true">
    </lightning-datatable>
</div>
</template>

lazyLoadingLWCDemo,js

import { LightningElement} from 'lwc';
import getContact from '@salesforce/apex/LazyLoadingController.getContact';

const columns = [
    { label: 'Id', fieldName: 'Id', type: 'text' },
    { label: 'Name', fieldName: 'Name', type: 'text'}
];

export default class LazyLoadingLWCDemo extends LightningElement {
    contacts=[];
    error;
    columns = columns;
    rowLimit =25;
    rowOffSet=0;
 
    connectedCallback() {
        this.loadData();
    }

    loadData(){
        return  getContact({ limitSize: this.rowLimit , offset : this.rowOffSet })
        .then(result => {
           let updatedRecords = [...this.contacts, ...result];
            this.contacts = updatedRecords;
            this.error = undefined;
        })
        .catch(error => {
            this.error = error;
            this.contacts = undefined;
        });
    }

    loadMoreData(event) {
        const currentRecord = this.contacts;
        const { target } = event;
        target.isLoading = true;

        this.rowOffSet = this.rowOffSet + this.rowLimit;
        this.loadData()
            .then(()=> {
                target.isLoading = false;
            });  
    }


}

XML

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



Sunday 19 June 2022

 getRelatedListsInfo

Use this wire adapter to get the metadata for RelatedLists in an object’s default layout.

Parameters

  • parentObjectApiName—(Required) The API name of a parent object that you want to get related lists for, like an Account.
  • recordTypeId—(Optional) The ID of the parent record type.

Usage

This code example fetches the related lists info by API name of the parent object, then iterates through the related lists.

HTML

<template>
    <lightning-card title="Related List of Account">
        <template if:true={relatedLists}>
            <div class="slds-m-around_medium">
                <template for:each={relatedLists} for:item="relatedList">
                    <p key={relatedList.label}>
                        {relatedList.label}
                    </p>
                </template>
            </div>
        </template>
    </lightning-card>
</template>


JS

import { LightningElement,wire} from 'lwc';
import { getRelatedListsInfo } from 'lightning/uiRelatedListApi';
export default class GetRelatedListDetails extends LightningElement {
    error;
    relatedLists;
    @wire(getRelatedListsInfo, {
        parentObjectApiName: 'Account',
       
    })listInfo({ error, data }) {
        if (data) {
            this.relatedLists = data.relatedLists;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.relatedLists = undefined;
        }
    }
}

XML

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

</LightningComponentBundle>

RESULT:





 getRelatedListRecords

Use this wire adapter to get RelatedList records.

Parameters

  • parentRecordId—(Required) The ID of the parent record that you want to get related lists for, like an Account ID.
  • relatedListId—(Required) The API name of a related list object, like Contacts, Opportunities, or Cases.
  • fields—(Optional) The API names of the related list’s column fields.
  • optionalFields—(Optional) The API names of additional fields in the related list.
  • pageSize—(Optional) The number of list records to return per page.
  • sortBy—(Optional) An array of field API names to sort the related list by. Accepts only one value per request.
  • where—(Optional) The filter to apply to related list records, in GraphQL syntax.
This code example fetches the record for the Opportunity-related list in the Account object, then iterates the opportunity to display the Id and Name.


HTML

<template>
    <lightning-card title="Opportunity Related List Records">
        <template if:true={records}>
            <div class="slds-m-around_medium">
                <template for:each={records} for:item="rec">
                    <p key={rec.fields.Id.value}>
                        {rec.fields.Id.value} -  {rec.fields.Name.value}
                    </p>
                </template>
            </div>
        </template>
    </lightning-card>

</template>

JS
import { LightningElement,wire} from 'lwc';
import { getRelatedListRecords } from 'lightning/uiRelatedListApi';
export default class GetRelatedListRecords extends LightningElement {
    error;
    records;
    @wire(getRelatedListRecords, {
        parentRecordId: '0010I00002Zq6IMQAZ',
        relatedListId: 'Opportunities',
        fields: ['Opportunity.Id','Opportunity.Name']
    })listInfo({ error, data }) {
        if (data) {
            this.records = data.records;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.records = undefined;
        }
    }
}

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

</LightningComponentBundle>


RESULT




 getRelatedListInfo

Use this wire adapter to get the metadata for RelatedList.

  • parentObjectApiName—(Required) The API name of a parent object that you want to get related lists for, like an Account.
  • relatedListId—(Required) The API name of a related list object such as Contacts, Opportunities, or Cases.
  • recordTypeId—(Optional) The ID of the parent record type. If not provided, the default record type is used.

This code example fetches the metadata for the Opportunity-related list in the Account object, then iterates through the list of display columns.


HTML

<template>
    <lightning-card title="Get Opportunity Related List Information">
        <template if:true={displayColumns}>
            <div class="slds-m-around_medium">
                <template for:each={displayColumns} for:item="info">
                    <p key={info.fieldApiName}>
                        {info.label}
                    </p>
                </template>
            </div>
        </template>
    </lightning-card>
</template>

JS

import { LightningElement,wire } from 'lwc';
import { getRelatedListInfo } from 'lightning/uiRelatedListApi';
export default class GetRelatedListInfo extends LightningElement {
    error;
    displayColumns;
    @wire(getRelatedListInfo, {
        parentObjectApiName: 'Account',
        relatedListId: 'Opportunities',
    })listInfo({ error, data }) {
        if (data) {
            console.log('data',JSON.stringify(data))
            this.displayColumns = data.displayColumns;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.displayColumns = undefined;
        }
    }
}

XML

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

RESULT








Get Related List Record Count

Use this wire adapter to get the RelatedList record count.

 This code example fetches the record count for a related list.

  • parentRecordId—(Required) The ID of the parent record that you want to get related lists for, like an Account ID.
  • relatedListId—(Required) The API name of a related list object such as Contacts, Opportunities, or Cases.

HTML

<template>
    <lightning-card title="getRelatedListCount">
        <div class="slds-var-p-around_medium">
          <template if:true={responseData}>
            <div>No of opportunities in account related list - {responseData.count}</div>
          </template>
        </div>
      </lightning-card>
</template>

JS

import { LightningElement,wire} from 'lwc';
import {getRelatedListCount} from 'lightning/uiRelatedListApi';
export default class GetReleatedListCount extends LightningElement {
    responseData;
    error;
    @wire(getRelatedListCount, {
      parentRecordId:'0010I00002Zq6IMQAZ', // AccountId
      relatedListId:'Opportunities' //RelatedList object Name
    })listInfo({error, data}){
      if(data){
         this.responseData = data;
         this.error = undefined;
      }
      if(error){
        this.error = error;
        this.responseData = undefined;
      }
    }
  }
 

XML

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

</LightningComponentBundle>

RESULT




Sunday 6 March 2022

                              ONLOAD IN AURA VS LIGHTNING WEB COMPONENT

If we embedded LWC component inside the aura component which onload method will call first (doinit/connectCallback)?. For understanding this we are going to create two Lightning components.

  1. customAuraComponent – Aura Component 
  2. customLwc – LWC Component.

Step 1: Create customAuraComponent  (Developer console -> New -> LightningComponent)

customAuraComponent 

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,
flexipage:availableForRecordHome,force:hasRecordId,
forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"></aura:handler>
    <lightning:card title="Cutsom Aura Component"></lightning:card>
    <!-- LWC Component -->
    <c:customLwc/>
</aura:component>


Javascript

doinit:function(component, event, helper) {          console.log('onload:aura component') }


Step 2: Create LWC component 

customLwc
<template>
    <p> LWC Component</p>
</template>

Javascript
import { LightningElement } from 'lwc';

export default class CustomLwc extends LightningElement {
    connectedCallback(){
        console.log("onload:LWC Component");
    }
}


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


Result :

The init handler in Aura gets fired first then connectedCallback in Lightning Web Component





Saturday 5 March 2022

                                DYNAMIC CSS IN LIGHTNING WEB COMPONENT

This post explains how to create CSS in lightning web components and also how to use the dynamic CSS in web components using the getter property

Let’s see an example. I have created a Lightning web component named dynamic style. It has a div and a checkbox. Our aim is to change the CSS class of div whenever the checkbox is checked.

dynamicStyle.html

<template>
    <lightning-card title="Dynamic CSS using Getter">
        <div class={dynamicColorChange}>
            Dynamic Style
        </div>
        <lightning-input type="checkbox" label="ChangeStyle" value={changeColor} onchange={handleChange}>
        </lightning-input>
    </lightning-card>
</template>

Javascript

import { LightningElement } from 'lwc';

export default class DynamicStyle extends LightningElement {
    changeColor;
    handleChange(event){
        this.changeColor=event.target.checked;  
    }

    //If change color is true: using getter will return class 1 else class 2
    get dynamicColorChange(){
        return this.changeColor?'class1':'class2';
    }
}

     CSS: The same name as an LWC component and add .css in the file name for this example: dynamicStyle.css

.class1{
   height: 30px;
   background-color: aqua;
}

.class2{
    height:30px;
     background-color: chartreuse;
}


     The onchange handler is defined in the dynamicStyle.js file of the component. It is updating the value of the checkbox to a property defined. Along with it, the js file also has a getter to compute dynamically the CSS class of the div block defined in HTML.