Sunday 29 September 2024

How to define generic null check of fields ?

 Use Case : Lets say you have a requirement to copy modified field values from latest opportunity to Account , then how can you do field mapping effectively ? 

Assumptions: We are not using any flows here. 

Step - 1 Get all Account Ids from Opportunity Trigger/trigger helper

Step -2 Query Account and Its related opportunity records, assume you want to define latest opportunity by LastStageChangeDate, you can use createdDate too. This will give account details and latest opportunity without the new values that has been modified. so this is basically old opportunity. 

private static List<Account> getAccounts(set<id> accountIdset){
    return [SELECT id,Field_1__c,Field_2__c,Field_3__c,Field_4__c,PersonEmail,Phone,
                               
            (SELECT id,Field_1__c,Field_2__c,Field_3__c,Field_4__c, Email__c,Phone__c
            FROM opportunities
            WHERE stagename = 'Admit' OR stagename = 'Return From Hospital'
            ORDER BY laststagechangeDate DESC LIMIT 1)
            FROM Account where Id IN: accountIdset WITH User_Mode];
}

Step - 3 Create a Map key as AccountId and value as Opportunity from trigger helper. This opportunity will be considered as new opportunity.

Step - 4 Iterate over Account records, under account list there will be another loop to iterate opportunity but that will be one record. when old opportunity Id and new opportunity id same that means latest opportunity is modified. Will leave up to you to find latest records. Now comes field mapping

Step - 5 Field Mapping 

 if(oldOppy.Id == newOppy.Id){
    if(newOppy.Field_1__c !=null){
        account.Field_1__c = newOppy.Field_1__c ;
    }
    if(newOppy.Field_2__c !=null){
        account.Field_2__c = newOppy.Field_2__c ;
    }
    if(newOppy.Field_3__c !=null){
        account.Field_3__c = newOppy.Field_3__c ;
    }
    if(newOppy.Field_4__c !=null){
        account.Field_4__c = newOppy.Field_4__c ;
    }

 } 

If you have few fields, then it is ok, if you need to map 100 fields then 100 ifs need to written, this is code redundancy, What if you need to get values from other object say Case then ?

So Instead of writing multiple Ifs , we can have one generic utility method that will work across object and field. 

Here is generic method 

 public Static void updateFieldIfNotNull(SObject record, String fieldName, Object fieldValue){
    if (fieldValue != null) {
            record.put(fieldName, fieldValue);
     }
       
}

Calling generic method.
 if(oldOppy.Id == newOppy.Id){
    updateFieldIfNotNull(acc,'Field_1__c',newOppy.Field_1__c);
    updateFieldIfNotNull(acc,'Field_2__c',newOppy.Field_2__c);
    updateFieldIfNotNull(acc,'Field_3__c',newOppy.Field_3__c);
    updateFieldIfNotNull(acc,'Field_4__c',newOppy.Field_4__c);
   
 }
Now code is short and readable.
Please try this approach and let me know in comments if this is useful for you.
Keep Learning !!


Thursday 26 September 2024

How to update only one latest child record's from list of Parent records ?

 This post is all about how to use aggregate query effectively or write less complex apex code.

Use Case: Lets say you need to update latest case record of each opportunity and  you have been given list of opportunity Ids. One opportunity can have multiple cases. How can you do it?

Approach - 1 If you are strong in SQL, you might be linking to use Group By Opportunity__c Order By CreatedDate Desc and Limit 1. SOQL does not support Order By limit along with Group By.

Approach - 2 Using Map to hold Opportunity Id with latest Case

Here is sample code 

// List of Opportunity IDs
List<Id> opportunityIds = new List<Id>{'oppId1', 'oppId2', 'oppId3'};

// Map to hold the latest Case for each Opportunity
Map<Id, Case> latestCaseMap = new Map<Id, Case>();
// Query all cases related to the Opportunity IDs,
sorted by CreatedDate descending to get the latest case first
List<Case> cases = [
    SELECT Id, Opportunity__c, Subject, Status, CreatedDate
    FROM Case
    WHERE Opportunity__c IN :opportunityIds
    ORDER BY CreatedDate DESC
];
// Loop through the cases and store the latest case for each Opportunity ID
for (Case c : cases) {
    Id oppId = c.Opportunity__c; // Assuming 'Opportunity__c'
is the lookup field on the Case object
   
    // If this Opportunity ID is not already in the map, add the current case
as the latest case
    if (!latestCaseMap.containsKey(oppId)) {
        latestCaseMap.put(oppId, c);
    }
    // Since the cases are already sorted by CreatedDate DESC, the first case
encountered is the latest one,
    // so no need to process further cases for the same Opportunity.
}

// Now latestCaseMap contains each Opportunity ID and its corresponding latest Case.
// You can iterate over it and perform the necessary update for each latest Case

List<Case> casesToUpdate = new List<Case>();
for (Id oppId : latestCaseMap.keySet()) {
    Case latestCase = latestCaseMap.get(oppId);    
    // Perform any necessary updates on the latest case
    latestCase.Status = 'Closed'; // Example: updating the status to 'Closed'
   
    // Add the case to the list for DML update
    casesToUpdate.add(latestCase);
}
// Update the latest cases for each Opportunity
if (!casesToUpdate.isEmpty()) {
    update casesToUpdate;
}
System.debug('Updated the latest case for each Opportunity.');

We can accomplish requirement in approach -2, but this is not efficient one.

Approach - 3 Using Aggregate Query.

Set<Id> caseIds = new Set<Id>();
List<Case> caseUpdateList = new List<Case>();
Case caseTemp;
// Query to get one Case ID per Approved_Lead__c (Opportunity)
List<AggregateResult> caseList = [
    SELECT Approved_Lead__c, Max(Id) caseId
    FROM Case
    WHERE Approved_Lead__c IN :oppyIds
    GROUP BY Approved_Lead__c
];

// Iterate through the results
for (AggregateResult ar : caseList) {
    Id opportunityId = (Id) ar.get('Approved_Lead__c'); // Opportunity ID (Approved_Lead__c)
    Id caseId = (Id) ar.get('caseId'); // The Case ID (MIN or MAX)
    caseIds.add(caseId);
    // Now you have the Opportunity ID and the Case ID
    System.debug('Opportunity ID: ' + opportunityId + ' Latest Case ID: ' + caseId);
}
for(Id cseId: caseIds){
caseTemp = new Case(Id=cseId, Status='Closed');
caseUpdateList.add(caseTemp);
}
If(!caseUpdateList.IsEmpty()){
    Update caseUpdateList;
}



  

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