Category Archives: Salesforce

Regex Matcher In Apex

The blow code is replacing the SSN number with * from a sentence.

Sample Code:

String searchText = 'This is your SSN 000-45-6789 number';
Pattern objPattern = Pattern.compile('[0-9]{3}-[0-9]{2}-[0-9]{4}');
String result = objPattern.matcher(searchText).replaceAll('***-**-****');
System.debug('searchText-' + searchText);
System.debug('result-' + result);

1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.00 out of 5)
Loading...

LWC Navigate Record Detail Page To New Browser Tab

import { LightningElement, track } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class TestComponent extends NavigationMixin(LightningElement) {

    @track accountId = '0018G00000KsFcJQAV';

    handlenavigateToAccountViewPage(event) {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.accountId,
                objectApiName: 'Account',
                actionName: 'view'
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }
}

Get Weekly Days Business Hours Difference

BusinessHours bh = [SELECT Id, Name, IsActive, IsDefault, SundayStartTime, SundayEndTime, 
                    MondayStartTime, MondayEndTime, TuesdayStartTime, TuesdayEndTime, 
                    WednesdayStartTime, WednesdayEndTime, ThursdayStartTime, ThursdayEndTime,
                    FridayStartTime, FridayEndTime, SaturdayStartTime, SaturdayEndTime,
                    TimeZoneSidKey FROM BusinessHours WHERE IsDefault = true];

DateTime startTime;
DateTime endTime;
Datetime dt = System.now();
String dayOfWeek = dt.format('EEEE');

if(dayOfWeek.equalsIgnoreCase('Saunday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.SundayStartTime.hour(), bh.SundayStartTime.minute(), bh.SundayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.SundayEndTime.hour(), bh.SundayEndTime.minute(), bh.SundayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('Monday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.MondayStartTime.hour(), bh.MondayStartTime.minute(), bh.MondayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.MondayEndTime.hour(), bh.MondayEndTime.minute(), bh.MondayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('TuesDay')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.TuesdayStartTime.hour(), bh.TuesdayStartTime.minute(), bh.TuesdayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.TuesdayEndTime.hour(), bh.TuesdayEndTime.minute(), bh.TuesdayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('Wednesday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.WednesdayStartTime.hour(), bh.WednesdayStartTime.minute(), bh.WednesdayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.WednesdayEndTime.hour(), bh.WednesdayEndTime.minute(), bh.WednesdayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('Thursday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.ThursdayStartTime.hour(), bh.ThursdayStartTime.minute(), bh.ThursdayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.ThursdayEndTime.hour(), bh.ThursdayEndTime.minute(), bh.ThursdayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('Friday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.FridayStartTime.hour(), bh.FridayStartTime.minute(), bh.FridayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.FridayEndTime.hour(), bh.FridayEndTime.minute(), bh.FridayEndTime.second(), 0));
}else if(dayOfWeek.equalsIgnoreCase('Saturday')){
    startTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.SaturdayStartTime.hour(), bh.SaturdayStartTime.minute(), bh.SaturdayStartTime.second(), 0));
    endTime = DateTime.newInstance(Date.today(), Time.newInstance(bh.SaturdayEndTime.hour(), bh.SaturdayEndTime.minute(), bh.SaturdayEndTime.second(), 0));
}

//get the difference between start time and end time
Long difference = BusinessHours.diff(bh.id, starttime, endtime);
Double hours = difference/3600000;
System.debug('Business Hours Diff-' + hours);

Lightning Web Component(LWC) Toast Messages

A component can send a toast notification that pops up to alert users of a success, error, or warning. A toast can also simply provide information. To display a toast notification in Lightning Experience or Lightning communities, import ShowToastEvent from the lightning/platformShowToastEvent module. Here is the example to show Lightning Web Component(LWC) Toast Messages.

Toast Event Properties:

Parameter Type Description
title String (Required) The title of the toast, displayed as a heading.
message String (Required) A string representing the body of the message. It can contain placeholders in the form of {0} ... {N}. The placeholders are replaced with the links on messageData.
messageData String[] or Object url and label values that replace the {index} placeholders in the message string.
variant String Changes the appearance of the notice. Toasts inherit styling from toasts in the Lightning Design System. Valid values are: info (default), success, warning, and error.
mode String Determines how persistent the toast is. Valid values are: dismissable (default), remains visible until you click the close button or 3 seconds has elapsed, whichever comes first; pester, remains visible for 3 seconds and disappears automatically. No close button is provided; sticky, remains visible until you click the close button.

LWCToastMessage.html:

<template>
    <lightning-button label="Success" onclick={showSuccess}></lightning-button>&nbsp;
    <lightning-button label="Error" onclick={showError}></lightning-button>&nbsp;
    <lightning-button label="Warning" onclick={showWarning}></lightning-button>&nbsp;
    <lightning-button label="Information" onclick={showInfo}></lightning-button>&nbsp;
</template>

LWCToastMessage.js:

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LWCToastMessages extends LightningElement {

    showError() {
        const evt = new ShowToastEvent({
            title: 'Error',
            message: 'This is an error message',
            variant: 'error',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showSuccess(){
        const evt = new ShowToastEvent({
            title: 'Success',
            message: 'This is a success message',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showWarning(){
        const evt = new ShowToastEvent({
            title: 'Warning',
            message: 'This is a warning message',
            variant: 'warning',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    showInfo() {
        const evt = new ShowToastEvent({
            title: 'Info',
            message: 'This is an information message',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}

LWCToastMessage.js-meta.xml:

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




Salesforce LWC Custom Datatable Pagination

Apex Class:

public class AccountController {
    
    @AuraEnabled//Get Account Records
    public static String getAccountList(Integer pageSize, Integer pageNumber){
        String jsonDT = '';
        
        //Offset for SOQL
        Integer offset = (pageNumber - 1) * pageSize;
        
        //Total Records
        Integer totalRecords = [SELECT COUNT() FROM Account];
        Integer recordEnd = pageSize * pageNumber;
        
        AccountDTWrapper objDT =  new AccountDTWrapper();  
        objDT.pageSize = pageSize;
        objDT.pageNumber = pageNumber;
        objDT.recordStart = offset + 1;
        objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
        objDT.totalRecords = totalRecords;
        objDT.accounts = [SELECT Id, Name, AccountNumber, Industry, Phone FROM Account LIMIT :pageSize OFFSET :offset];
        jsonDT = JSON.serialize(objDT);
        return jsonDT;
    }
    
    public class AccountDTWrapper {
        public Integer pageSize {get;set;}
        public Integer pageNumber {get;set;}
        public Integer totalRecords {get;set;}
        public Integer recordStart {get;set;}
        public Integer recordEnd {get;set;}
        public List<Account> accounts {get;set;}
    }
}

accountList.html

<template>
    <template if:true={loader}>
        <lightning-spinner alternative-text="Loading..." size="small"></lightning-spinner>
    </template>

    <div class="slds-box slds-theme_default">
        <lightning-card  title="Accounts">
            <table class="slds-table slds-table_cell-buffer slds-table_bordered">
                <thead>
                    <tr class="slds-line-height_reset slds-text-title_caps">
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Name">
                                Name
                            </div>
                        </th>
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Account Number">
                                Account Number
                            </div>
                        </th>
                        <th  class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Industry">
                                Industry
                            </div>
                        </th>
                        <th class="slds-is-resizable" scope="col">
                            <div class="slds-truncate" title="Phone">
                                Phone
                            </div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template if:true={accounts}>
                        <template for:each={accounts} for:item="acc">
                            <tr key={acc.Id}>
                                <th scope="row" data-label="Name">
                                    <div class="slds-truncate" title={acc.Name}>{acc.Name}</div>
                                </th>
                                <th scope="row" data-label="Account Number">
                                    <div class="slds-truncate" title={acc.AccountNumber}>{acc.AccountNumber}</div>
                                </th>
                                <th scope="row" data-label="Industry">
                                    <div class="slds-truncate" title={acc.Industry}>{acc.Industry}</div>
                                </th>
                                <th scope="row" data-label="Phone">
                                    <template if:true={acc.Phone}>
                                    <div class="slds-truncate" title={acc.Phone}>{acc.Phone}</div>
                                </template>
                                </th>
                            </tr>
                        </template>
                    </template>
                </tbody>
            </table>
            <template if:true={isDisplayNoRecords}>
                <div class="slds-align_absolute-center">
                    <br/>
                    No records found
                </div>
            </template>
            <br/>
            <div class="slds-align_absolute-center"> 
                <div class="slds-p-right_xx-small">
                        
                    <lightning-button label="Prev"
                    disabled={isPrev} onclick={handlePrev}
                                        variant="brand"
                                        icon-name="utility:back"
                                        name="prev"></lightning-button>  
                </div>
                <span class="slds-badge slds-badge_lightest">
                    {recordStart}-{recordEnd} of {totalRecords} | Page {pageNumber} of {totalPages}
                </span>
                <div class="slds-p-left_xx-small">
                    <lightning-button label="Next"
                    disabled={isNext} onclick={handleNext}
                                        variant="brand"
                                        icon-name="utility:forward"
                                        icon-position="right"
                                        name="next"></lightning-button>
                </div>
            </div>  
        </lightning-card>
    </div>
</template>

accountList.js

import { LightningElement, wire, api, track  } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';

export default class AccountList extends LightningElement {
    @track loader = false;
    @track error = null;
    @track pageSize = 10;
    @track pageNumber = 1;
    @track totalRecords = 0;
    @track totalPages = 0;
    @track recordEnd = 0;
    @track recordStart = 0;
    @track isPrev = true;
    @track isNext = true;
    @track accounts = [];

    //On load
    connectedCallback() {
        this.getAccounts();
    }

    //handle next
    handleNext(){
        this.pageNumber = this.pageNumber+1;
        this.getAccounts();
    }

    //handle prev
    handlePrev(){
        this.pageNumber = this.pageNumber-1;
        this.getAccounts();
    }

    //get accounts
    getAccounts(){
        this.loader = true;
        getAccountList({pageSize: this.pageSize, pageNumber : this.pageNumber})
        .then(result => {
            this.loader = false;
            if(result){
                var resultData = JSON.parse(result);
                this.accounts = resultData.accounts;
                this.pageNumber = resultData.pageNumber;
                this.totalRecords = resultData.totalRecords;
                this.recordStart = resultData.recordStart;
                this.recordEnd = resultData.recordEnd;
                this.totalPages = Math.ceil(resultData.totalRecords / this.pageSize);
                this.isNext = (this.pageNumber == this.totalPages || this.totalPages == 0);
                this.isPrev = (this.pageNumber == 1 || this.totalRecords < this.pageSize);
            }
        })
        .catch(error => {
            this.loader = false;
            this.error = error;
        });
    }

    //display no records
    get isDisplayNoRecords() {
        var isDisplay = true;
        if(this.accounts){
            if(this.accounts.length == 0){
                isDisplay = true;
            }else{
                isDisplay = false;
            }
        }
        return isDisplay;
    }
}

accountList.js-meta.xml

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