Monday 17 April 2023

How to get record type name from recordId in Lighting Component without Apex ?

 First, the code imports the getRecord wire adapter from the lightning/uiRecordApi module, which is built on Lightning Data Service. Then it defines the fields (Recordtypeid,recordtypename])to pass to the wire adapter.

The @wire decorator tells getRecord to get the values of the specified fields on the record with the specified $recordId. The $ means that the value is passed dynamically. When the value changes, the wire service provisions data and the component rerenders.

The data is provisioned to the data and error objects of the property decorated with @wire.

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

import { getRecord } from 'lightning/uiRecordApi';
import CASE_RECORDTYPEID from '@salesforce/schema/Case.RecordType.Id'
import CASE_RECORDTYPENAME from '@salesforce/schema/Case.RecordType.Name'
const _FIELDS = [CASE_RECORDTYPEID,CASE_RECORDTYPENAME];
export default class PlanOfCareTab extends LightningElement {
    @api recordId;
    caseRec;
    recordtypeName;

   
    @wire(getRecord, { recordId: '$recordId', fields: _FIELDS })
    wiredRecord ({data, error} ) {
        console.log(' data----34--', JSON.stringify(data));
        if(data){
            this.caseRec = data;
            console.log(' this.caseRec--', JSON.stringify(this.caseRec));
            this.recordtypeName =
JSON.stringify(this.caseRec.fields.RecordType.value.fields.Name.value);
            this.recordtypeName = this.recordtypeName.replace(/"/gi, ""); // replaces ""
   
        }
        if(error){
            console.log('error occured');
        }
    }

}

Tuesday 11 April 2023

How to download selected multiple files for a record using LWC component?

 Here is the LWC component, can be added to record page.

Apex Class

public class MultipleFilesDownLoadController {
    @AuraEnabled()
    public static  List<ContentDocumentLink> retriveFiles(String sLinkEntityId) {
        system.debug('sLinkEntityId--'+sLinkEntityId);
       
       List<ContentDocumentLink> listOfDocumentLink = [Select Id,ContentDocument.LatestPublishedVersionId,ContentDocumentId,ContentDocument.Title,ContentDocument.Owner.Name
                                                        FROM ContentDocumentLink
                                                       WHERE LinkedEntityId =:sLinkEntityId];
         system.debug('listOfDocumentLink---'+listOfDocumentLink);
        return  listOfDocumentLink;
    }
}

Component

<template>

    <lightning-card  variant="Narrow"  title="Files" icon-name="standard:file">
         <p slot="actions">
            <lightning-button class="slds-m-right_x-small slds-float_right" 
            variant="brand" label="Download"  onclick={downloadFiles
            icon-name="utility:download" >
            </lightning-button>
        </p> 
        <p class="slds-p-horizontal_small">
            <lightning-datatable data={filesData
                columns={columns
                key-field="id">
            </lightning-datatable>
        </p>    
    </lightning-card>    
</template>

JS Controller 

import { LightningElement,api } from 'lwc';
import retriveFiles from '@salesforce/apex/MultipleFilesDownLoadController.retriveFiles';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
const columns = [
    {label: 'Title', fieldName: 'Title'},  
    {label: 'Owner', fieldName: 'Owner'}          
];
export default class MultipleFilesDownLoad extends NavigationMixin (LightningElement) {
     @api recordId;
     @api columns = columns;
      filesData;
     sSelectedId = [];
     
     connectedCallback() {
        console.log('connected===============');
        console.log(this.recordId);
        if(this.recordId){
            retriveFiles({sLinkEntityId: this.recordId})
            .then(res => {
               console.log('intiala files ',JSON.stringify( res ) );
                 let tempRecords = JSON.parse( JSON.stringify( res ) );
                 console.log('tempRecords--',tempRecords);
                    tempRecords = tempRecords.map( row => {
                    return { ...row, Id:row.ContentDocument.LatestPublishedVersionId,Owner: row.ContentDocument.Owner.Name,Title:row.ContentDocument.Title};
                });
                this.filesData = tempRecords;
            }).catch(err => {
                console.log('error', err);
                this.showError(err.body.message);
            });
        }
    }

     showError(msg){
        const evt = new ShowToastEvent({
            title: 'File delete Error',
            message: msg,
            variant: "error"
        });
        this.dispatchEvent(evt);
    }
    

    downloadFiles(){
        var selectedRecords = this.template.querySelector("lightning-datatable").getSelectedRows(); 
        console.log('selectedRecords--'+JSON.stringify(selectedRecords));
        //this.selectedFiles = selectedRecords;
        // this.sSelectedId = ''
        for (const svalue of selectedRecords) {
            console.log(svalue);
            if(this.sSelectedId){
                this.sSelectedId.push(svalue.Id);
            }       
        
        }
        console.log('this.sSelectedId==',this.sSelectedId);
        if(this.sSelectedId.length > 0){
            let filesDownloadUrl = '/sfc/servlet.shepherd/version/download';
            this.sSelectedId.forEach( item => {
                        filesDownloadUrl += '/' + item
             });
            thisNavigationMixin.Navigate ]( {
                        type: 'standard__webPage',
                        attributes: {
                            url: filesDownloadUrl
                        }
                    }, false );
            console.log( 'filesDownloadUrl is', filesDownloadUrl );
            this.dispatchEvent(
                        new ShowToastEvent( {
                            title: 'File(s) Download',
                            message: 'File(s) Download Successfully!!!',
                            variant: 'success'
                        } ),
                    );
        }
    }
}

XML 

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

Record Page



Wednesday 15 February 2023

How to add dynamic record link in HTML email template ?

 Sometimes we need to add record link in email template so that user can easily navigate.

Earlier {!Object.Link} was working in classic version, now It is not working in lighting , there is some idea you can vote for.

However there is a workaround to make it work.

{!MID(CustomObject__c.Link, 1, LEN(CustomObject__c.Link)-15)}{!CustomObject__c.Id}

!MID(Account.Link, 1, LEN(Account.Link)-15)}{!Account.Id}


Thursday 9 February 2023

How can I efficiently get a Set from a List ?

 Lets assume we have List<Account> record, we need to get all account record id in a set.

List<Account> accList = [select id,name from Account limit 10];

system.debug('acclist--'+accList);

We have accList , need to get account Record id,

Earlier approach is iterating over loop 

Set<Id> accidSet = new Set<Id>();

for(Account acc:accList ){

    accidSet.add(acc.id);

}

System.debug('accidSet--'+accidSet);

However the efficient way will be 

Set<Id> accidSet = (new Map<Id,Account>(accList)).keySet();

system.debug('accIdSet--'+accidSet);

Thursday 25 August 2022

Lifecycle hooks in LWC

There are 3 phase of LWC component 

1. Mounting 
A. constructor, B. connnectedCallback C. render D. renderedCallback

2. UnMounting 
A. disconnectedcallback

3. Error 
A.errorcallback

Note - render is not lifecycle hook, it is protected method of Lightning element class.

Mounting Phase

LWC Creation and Render Life cycle




















Constructor Method
·       This method called when component is instantiated and It flows from parent to child component.
·       Need to call Super() inside constructor method
·       Can’t access any component properties or child component because it’s not ready yet.
·       Host element can be accessed through “this. template” inside constructor method.
·       Don’t add any attributes to host inside constructor

C constructor(){
        super(); // This is mandatory
        console.log('parent component constructor called ');
        //var elements = this.template.querySelector('.demo'); // We cant do this coz component
is not loaded yet. however we can add event listener to whole component
       // console.log('elements..',elements);
    }

connectedCallBack Method
·       This method called when component is inserted into DOM and It flows from parent to child component.
·       Can’t access any  child component property because it’s not exists yet.
·       Host element can be accessed through “this. template” inside this method.
·       Use connectedCallBack to perform initialization task such as fetch data, set up caches,listen to publish-subscribe events or call apex method.
Dont use this method to change the state of component properties loading values or setting properties. Use getters and setters instead.

connectedCallback(){
        console.log('parent component connectedCallback called ');
       
 }
renderedCallback Method
·       This method called when component is rendered and It flows from child to parent component.
·       It can fired more than once, any changes made to component invokes this method again and again which impact performance
·      When component re-renders all expression used in the template are reevaluated 
·       Don’t use renderedCallback to change the state or update property of a component
Do not use rerenderedCallback to update wire adapter configuration object property, it will result infinite loop.

renderedCallback(){
        console.log('parent component renderedCallback called ');
       
}

UNMounting Phase

disconnectedCallback Method
·       This method called when component is removed from DOM
·       
It flows from Parent to child and it is specific Lightning Web component.

disconnectedCallback(){
        console.log('parent component disconnectedCallback called');
    }

Uses
1. disconnectedCallback can be used for performance improvement and memory leakage issue.
for example, If event listener or set Interval of window property set,
then It will be running behind the scene, we can remove (removeEventlistner or clearInterval)
in this method.

Error Phase

disconnectedCallback Method
This method called when  descended component throw an error.
errorCallBack have 2 arrgurment error object and stack argument as String

errorCallback(error,stack){
        console.log('stack',stack);
        console.log('error',error);
        console.log('error message',error.message);
 }

render Method
  • render method is a protected method of Lighting Element Class.
  • This method tells the lightning engine which template to load based on some condition, The return type of this method is reference of template.
  • We dont have to keep writing all html code in html file, we can segregate to different html file. By using render method we can load. 
 Importing html file.
import secondHTML from './second.html';
import firstHTML from './first.html';

render(){

        return this.htmlFileName === 'secondHTML' ? :firstHTML;
       
    }




Friday 1 July 2022

How to map relationship query results to Lighting Data Table ?

We can not straight forward map relationship filed from apex to LWC data table. When we get query results related object information comes  as different object itself. So we need to traverse the query results and map the way we want to.

Hers is your controller method
@AuraEnabled(cacheable=true)
    public static List<Associated_Healthcare_Center__c> getAssociatedFacility(Id sLeadId,Id sAccountId){
       
    return [SELECT id,Signature_Healthcare_Center__c,Signature_Healthcare_Center__r.phone__c,
                 Signature_Healthcare_Center__r.Facility_Short_Name__c,
                 Signature_Healthcare_Center__r.Admission_Director__r.Name
                 FROM Associated_Healthcare_Center__c WHERE Account__c =:sAccountId 
                 Order By Signature_Healthcare_Center__r.Facility_Short_Name__c];
          
       
    }

Template Data table code 
      <div style="height: 300px;">
            <lightning-datatable
                    key-field="Signature_Healthcare_Center__c"
                    data={data}
                    columns={columns}>
            </lightning-datatable>
        </div>

Template Java script code.
import { LightningElement,api,wire,track} from 'lwc';
import getAssociatedFacility from '@salesforce/apex/AssignFacilityLWCController.getAssociatedFacility';

const columns = [
    { label: 'Facility', fieldName: 'Facility' },
    { label: 'Admission Director', fieldName: 'AdmissionDirector', type: 'text' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    
];
export default class AssignFacilityLWCModal extends LightningElement {
    @api recordId;
    @api accountId;
   
    @track data;
    @track columns = columns;
    @track error;

    /*connectedCallback() {
       console.log('Inside chield component record Id -->',this.recordId);
       if(this.recordId){
           getAssociatedFacility({sLeadId:this.recordId,sAccountId:this.accountId})
            .then(result=>{
                console.log('result-->',result);
            }).catch(err => {
                console.log('err',err)
                this.showError(err.message);
            });

       }
       
    }*/
    @wire(getAssociatedFacility,{sLeadId:'$recordId',sAccountId:'$accountId'})
    getAssociatedFacilityWired({ error, data }) {
        if (data) {
            
            
               let tempRecords = JSON.parse( JSON.stringify( data ) );
                    tempRecords = tempRecords.map( row => {
                    return { ...row, Facility: row.Signature_Healthcare_Center__r.Facility_Short_Name__c,
AdmissionDirector: row.Signature_Healthcare_Center__r.Admission_Director__r.Name
Phone: row.Signature_Healthcare_Center__r.Phone__c };
                });
                 console.log(' this.datempRecordta-->'this.tempRecords);
                this.data = tempRecords;
           
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }

In Console this is how query results will be shown before mapping

Here is actual Output




Tuesday 3 May 2022

Style in LWC

 Following are the ways we can apply in CSS in LWC.

1. Inline CCS

Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div
<template>
    <lightning-card title="Inline CSS">
        <div>
            <div style="color:green;font-size:10px;">This is inline Style div</div>
        </div>
    </lightning-card>
</template>

 2. External CSS
style can be applied to an elements such as h1, p,div span etc.
It can applied to class using "." notation. for example .user{}
It can also be applied to pseudo class.  for example .user:hover{}
Id locator is not being used in LWC to apply style

To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is externalCSS then file name should be "externalCSS .css"

<template>   
    <lightning-card title="External CSS">
        <div>
            <div class="externalDiv">This is External Style div</div>
            <p> This is a p Tag</p>
        </div>
    </lightning-card>
</template>

CSS File.
.externalDiv{
    background-color: yellow;
    color:blue;
    font-size:20px;
}
p{
    color:green;
    font: size 20px;
    border: 1px solid red;
}
.externalDiv:hover{
    background-color: white;
    color:red;
    font-size:50px;
}

3. Lightning Design System.
Its a salesforce standard style library.- https://www.lightningdesignsystem.com/
slds-var-p-horizontal_medium. Few more examples margin,grid,batch,text style,box,brand. 
We can search what CSS/stylesheet code needed, copy pseudo code

<template>
    <lightning-card title="SLDS">
        <div class="slds-var-p-horizontal_medium">
            <div class=" slds-box ">
                <p>This is a regular-sized box.</p>
                <span class="slds-badge">Badge Label</span>
                <span class="slds-badge slds-theme_success">Badge Success</span>
              </div>
        </div
       
    </lightning-card>
    <lightning-card>
        <div class="slds-brand-band slds-brand-band_medium slds-brand-band_group"></div>
    </lightning-card>

</template>

4.  Design Token.
Design tokens are the visual design atoms of the design system — specifically, they are named entities that store visual design attributes. We use them in place of hard-coded values (such as hex values for color or pixel values for spacing) in order to maintain a scalable and consistent visual system for UI development.
Note - Only global action design token can be used in salesforce platform for styling.
Instead of using hard code value we can use token. for example. To have blue text color and white background we can define CSS like 
div{
    color: var(--lwc-brandTextLink);
    background:var(--lwc-brandPrimaryTransparent);
}

5. Shared CSS
When we have common CSS code which are required to be used in multiple components at that time shared CSS is expected to be used. this approach will  code redundancy and easy to maintain.

Assume we have 2 components, component 1 and component 2. both components have common CSS code along with individual CSS code.
 Step - 1 : Create a LWC component named as sharedCSSLWC.
Step -2 : Delete html and JS file from component bundle
Step - 3 : Create CSS file named as sharedCSSLWC.css
Step- 4 : Add common CSS code.
Step - 5 : Go to CSS file of component 1 and import sharedCSSLWC
Step - 6   Go to CSS file of component 2 and import sharedCSSLWC

SharedCSSLWC.css
.mainDiv{
    width:100%;
    background-color: #ddd;
}
.internalDiv{
    text-align:right;
    padding-top:10px;
    padding-bottom: 10px;
    color:white;
}
Component1.css
@import 'c/sharedCSSLWC';
.p{
    width:90%;
    background-color:green;
}
Component2.css
@import 'c/sharedCSSLWC';
.css{
    width:80%;
    background-color:#2196f3;
}

6. Dynamic Styling
Sometime we have assign CSS dynamically. To do so we need to use getter. Assume on user input div width will be controlled. 
There is an input box where percentage will be entered, based on entered value div width will be visible accordingly. 
style={percentage} is the getter.

<template>
    <lightning-card title="Dynamic CSS">

        <div class="slds-var-m-around_medium">
            <lightning-input label="Percentage" type="Number"
                onkeyup={changeHandler} value={percent}>

            </lightning-input>
            <div  style={percentage} class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_error" role="alert">
                This is an alert !!!
            </div>
        </div>
    </lightning-card>

</template>
JS file
import { LightningElement } from 'lwc';

export default class DynamicCSS extends LightningElement {
    percent=10;
    changeHandler(event){
        this.percent = event.target.value;
    }

    get percentage(){
        return `width: ${this.percent}%`;
    }
}

7. Styling Across Shadow DOM
This is required when we need to override standard salesforce style. this is not advisable though. We need to follow this when there is no option left. This will have performance impact.

As per shadow dom concept CSS code will not cross boundary even if we apply CSS code externally it will not reach to shadow DOM, it will be applied to parent component. To apply CSS code we need to generate css code from Java script. here is sample code.

Here is component code, It only contains one button. I want to apply CSS to that button. Tried with external CSS by assign class. That class applied only outer element. It could not reach to shadow DOM <button>
<template>
    <lightning-card title="Shadow DOM">

        <div class="slds-var-m-around_medium">
            <lightning-button label="Test" title="Test" class="btnCSS></lightning-button>
        </div>
    </lightning-card>

</template>

To apply CSS to shadow DOM
shadow-d-o-m-l-w-c - component name referenced in kebab case.
Below code will create inline <style> //here css code  </style>tag inside button.
import { LightningElement } from 'lwc';
export default class ShadowDOMLWC extends LightningElement {
    isLoaded = false;
    renderedCallback(){
        if(this.isLoaded) return;
        const style = document.createElement('style');
        style.innerText = `c-shadow-d-o-m-l-w-c .slds-button{
            background: red;    
            color:white;
        }`;
        this.template.querySelector('lightning-button').appendChild(style);
        this.isLoaded = true;
    }
}