Saturday, April 25, 2020

Comparable Interface in Salesforce

The Comparable interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.

To add List sorting support for your Apex class, you must implement the Comparable interface with its compareTo method in your class.

When a class implements the Comparable interface it has to implement a method called compareTo(). This method returns an integer value that is the result of the comparison.

compareTo(objectToCompareTo)
Returns an integer value that is the result of the comparison.

The implementation of this method returns the following values:

0 if this instance and objectToCompareTo are equal
> 0 if this instance is greater than objectToCompareTo
< 0 if this instance is less than objectToCompareTo

If this object instance and objectToCompareTo are incompatible, a System.TypeException is thrown.

Example:
global class Employee implements Comparable {

    public Long id;
    public String name;
    public String phone;
    
    // Constructor
    public Employee(Long i, String n, String p) {
        id = i;
        name = n;
        phone = p;
    }
    
    // Implement the compareTo() method
    global Integer compareTo(Object compareTo) {
        Employee compareToEmp = (Employee)compareTo;
        if (id == compareToEmp.id) return 0;
        if (id > compareToEmp.id) return 1;
        return -1;        
    }
}

Sort the List using compareTo(object) method.
List<Employee> empList = new List<Employee>();
empList.add(new Employee(101,'Joe Smith', '4155551212'));
empList.add(new Employee(101,'J. Smith', '4155551212'));
empList.add(new Employee(25,'Caragh Smith', '4155551000'));
empList.add(new Employee(105,'Mario Ruiz', '4155551099'));

// Sort using the custom compareTo() method
empList.sort();

// Write list contents to the debug log
for (Employee emp : empList){
 system.debug(emp);
}

Output


Format Dates and Time using Apex in Salesforce


This post explains how to format dates and times using apex.
The below table contains the formatting codes.

LetterDate or Time PieceExamples
GEraG = AD
yYearyy = 09, yyyy = 2009
MMonthMM = 08, MMM = Aug, MMMMM = August
wWeek in yearw = 35
WWeek in monthW = 3
DDay in yearD = 235
dDay in monthdd = 27
FDay of week in monthF = 2
EDay in weekE = Thu, EEEEE = Thursday
aAM/PMa = AM or PM
HHour in day (0-23)HH = 23
kHour in day (1-24)kk = 24
KHour in am/pm (0-11)KK=11
hHour in am/pm (1-12)hh = 12
mMinutes in hourmm = 30
sSecond in minutess = 55
SMillisecond in secondSSS = 888
zTime zonez = EDT, zzzzz = Eastern Daylight Time
ZTime zone offsetZ = -0400

Examples
DateTime dt = Datetime.now();
String strTimeInAMorPM = dt.format('MMMMM dd, yyyy hh:mm:ss a');
System.debug('time in am and pm ==> '+strTimeInAMorPM); 

String strTimeInWeek = dt.format('MMMMM dd, yyyy EEEE');
System.debug('strTimeInWeek ==> '+strTimeInWeek); 

String strTimezone = dt.format('MMMMM dd, yyyy z');
System.debug('strTimezone ==> '+strTimezone); 

Output

Friday, April 17, 2020

Handle Custom Validations in Lightning Web Components(lwc)

When we working with input values some times users enter the bad data, In this situation we need to validate the data and show the custom error message to the user to correct the data.

Use the setCustomValidity() and reportValidity() methods to validate and dsiplay custom error message.

Demo:
HTML Code
<template>
    <lightning-card title="Custom Validations In Lightning Web Components">
        <lightning-input class="nameCmp" label="Enter Name" type="string"></lightning-input>
        <lightning-input class="dateCmp" label="Enter Date" type="date"></lightning-input><br/><br/>
        <lightning-button class="slds-align_absolute-center" label="Search" variant="brand" onclick={searchTheData}></lightning-button>
    </lightning-card>
</template>

Javascript Code
import { LightningElement, track } from 'lwc';

export default class DemoApp extends LightningElement {

    searchTheData() {
        let searchCmp = this.template.querySelector(".nameCmp");
        let dateCmp = this.template.querySelector(".dateCmp");
        let searchvalue = searchCmp.value;
        let dtValue = dateCmp.value;
       
        if (!searchvalue) {
            searchCmp.setCustomValidity("Name value is required");
        } else {
            searchCmp.setCustomValidity(""); // clear previous value
        }
        searchCmp.reportValidity();

        if (!dtValue) {
            dateCmp.setCustomValidity("Date value is required");
        } else {
            dateCmp.setCustomValidity(""); // clear previous value
        }
        dateCmp.reportValidity();
    }
}

Output