Wednesday, December 16, 2020

Access Custom Metadata Type data without Using the SOQL in Salesforce

From Spring'21 onwards we can get the custom metadata record information without using the SOQL.

Demo:

For the demo, I created the Country and Amount(Country_And_Amount__mdt) Custom Metadata type object and records.

Country_And_Amount__mdt object.


Sample Code:

// Getting all metadata values 
Map<String, Country_And_Amount__mdt> mapValues = Country_And_Amount__mdt.getAll();

for(Country_And_Amount__mdt mdt : mapValues.values()) {
    System.debug('Name => '+mdt.Label);
    System.debug('DeveloperName => '+mdt.DeveloperName);
    System.debug('Amount__c => '+mdt.Amount__c);
}


// Getting metadata record based on value
Country_And_Amount__mdt objMdt = Country_And_Amount__mdt.getInstance('United_States');
System.debug('objMdt => '+objMdt);


Output:



Tuesday, December 15, 2020

Inline Editing in lightning-datatable in Salesforce Lightning Web Component(lwc)

 This post explains, inline editing in lightning-datatable in salesforce lightning web components(lwc).


HTML Code:

<template>
    <lightning-card title="Inline Edit With Lightning Datatable in LWC">
        <template if:true={contacts.data}>
            <lightning-datatable key-field="Id" 
                                 data={contacts.data} 
                                 columns={columns} 
                                 onsave={handleSave}
                                 draft-values={saveDraftValues} 
                                 hide-checkbox-column 
                                 show-row-number-column>
            </lightning-datatable>
        </template>
    </lightning-card>
</template>


Javascript Code:

import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
// datatable columns
const columns = [
    {
        label: 'Name',
        fieldName: 'Name',
        type: 'text',
    }, {
        label: 'FirstName',
        fieldName: 'FirstName',
        type: 'text',
        editable: true,
    }, {
        label: 'LastName',
        fieldName: 'LastName',
        type: 'text',
        editable: true,
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone',
        editable: true
    }
];

export default class InlineEditTable extends LightningElement {

    columns = columns;
    @track contacts;
    saveDraftValues = [];

    @wire(getContacts)
    cons(result) {
        this.contacts = result;
        if (result.error) {
            this.contacts = undefined;
        }
    };

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

        // Updateing the records using the UiRecordAPi
        const promises = recordInputs.map(recordInput => updateRecord(recordInput));
        Promise.all(promises).then(res => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Records Updated Successfully!!',
                    variant: 'success'
                })
            );
            this.saveDraftValues = [];
            return this.refresh();
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'An Error Occured!!',
                    variant: 'error'
                })
            );
        }).finally(() => {
            this.saveDraftValues = [];
        });
    }

    // This function is used to refresh the table once data updated
    async refresh() {
        await refreshApex(this.contacts);
    }
}

Apex Code:

public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Phone, Email 
                FROM Contact 
                WHERE Email != null 
                AND Phone != null 
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
}


Output:



Tuesday, December 8, 2020

How to get object key prefix using apex in salesforce

This post explains how to get the object key prefix using apex in salesforce.

Below the code is to get the Account Key prefix.

Sample Code:

String strObjKeyPrefix  = Account.sobjecttype.getDescribe().getKeyPrefix();
system.debug('Key Prefix =>' +strObjKeyPrefix);
Output:



Monday, December 7, 2020

Hyperlink a Record in lightning-datatable in Lightning Web Components(lwc)

 This post explains how to add the Hyperlink to name in the lightning data table using Lightning web components(lwc).

Example:

HTML Code:

<template>
    <lightning-card title="Hyperlink to The Name in Lightning Datatable"><br/>
         <div if:true={consData}>
            <lightning-datatable data={consData} 
                                 columns={columns} 
                                 key-field="Id"
                                 hide-checkbox-column="true"></lightning-datatable>
        </div>
    </lightning-card>
</template>

Javascript Code:

import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';


// datatable columns
const columns = [
    {
        label: 'Name',
        fieldName: 'ConName',
        type: 'url',
        typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
    }, {
        label: 'FirstName',
        fieldName: 'FirstName',
        type: 'text',
    }, {
        label: 'LastName',
        fieldName: 'LastName',
        type: 'text',
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone'
    }
];

export default class HyperlinkNameInDatatable extends LightningElement {
    consData = [];
    columns = columns;

    @wire(getContacts)
    contacts({ error, data }) {

        if (data) {
            let tempConList = []; 
            
            data.forEach((record) => {
                let tempConRec = Object.assign({}, record);  
                tempConRec.ConName = '/' + tempConRec.Id;
                tempConList.push(tempConRec);
                
            });
            
            this.consData = tempConList;
            this.error = undefined;

            console.table(this.consData);

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

Apex Code:

public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Phone, Email 
                FROM Contact 
                WHERE Email != null 
                AND Phone != null 
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
}

Result:



Sunday, December 6, 2020

Address Lookup in Lightning Web Components(LWC) using Google Maps Places API

To Enable the address lookup in lightning-input-address first we need to enable the permission for Maps and Location Settings in our salesforce org.

Note: 

Maps and Location Settings feature only available in Professional, Enterprise, Performance, and Unlimited editions.

Path:

From Setup, enter Maps in the Quick Find box, and then select Maps and Location Settings


Once the permission is enabled, we need to provide the show-address-lookup attribute to display the Address Lookup field.

Example:

<template>
   <lightning-card title="Address Lookup using Google Maps Places API">
      <lightning-input-address  address-label="Shipping Address"
         street-label="Street"
         city-label="City"
         country-label="Country"
         province-label="Province"
         postal-code-label="PostalCode"
         street="Default Street Line"
         city=""
         country=""
         province=""
         postal-code=""
         required
         field-level-help="Select Shipping Address"
         show-address-lookup>
      </lightning-input-address>
   </lightning-card>
</template>

Output:




Tuesday, December 1, 2020

Safe Navigation Operator – Avoid Null Pointer Exceptions

Safe Navigation Operator (?.) first evaluates the Left-Hand-Side of the chain expression. If it is NULL, the Right-Hand-Side is evaluated and returns NULL. We can use this operator in variable, method, and property chaining.

To use the Safe Navigation Operator, we just need to replace the dot (.) with “?.“.

For Example,  Account?.Type.

Example: 1

// Creating a NULL reference.
Account objAcc; 

// it throws Null Pointer Exception.
System.debug(objAcc.Type); 

// it prints the NULL because we used the safe operator
System.debug(objAcc?.Type); 

Example: 2


Without Safe Navigation Operator:

String str = 'Salesforce Code Crack';
if(!String.isEmpty(str)){
    System.debug(str.capitalize());
}

With Safe Navigation Operator:

String str = 'Salesforce Code Crack';
System.debug(str?.capitalize());

Example: 3


Without Safe Navigation Operator:

list<Account> lstAccs = [SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH'];
if(lstAccs != null && !lstAccs.isEmpty()){
    System.debug(lstAccs[0].Type);
}

With Safe Navigation Operator:

System.debug([SELECT Type FROM Account WHERE Id='0013z00002TAEwaAAH' LIMIT 1]?.Type);

References: