Saturday, January 15, 2022

Display toast notifications in Lightning Web Component

Toast notification pops up to alert users of a success, error, or warning

We need to import ShowToastEvent from the lightning/platformShowToastEvent module to

display a toast notification in Lightning Experience or Experience Builder sites.

The important point to note is ShowToastEvent isn’t supported on login pages in Experience

Builder sites.

Success Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Success Message',

            message: 'Record inserted successfully ',

            variant: 'success',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Error Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Error Message',

            message: 'Record inserted failed ',

            variant: 'error',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Warning Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Warning Message',

            message: 'Some problem occured ',

            variant: 'warning',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

Info Toast:

showNotification() {

        const evt = new ShowToastEvent({

            title: 'Information Message',

            message: 'Operation running in background ',

            variant: 'info',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }


Let us understand the use with an example below.


<template>

    <lightning-card  title="Testing Toast In LWC">

        <lightning-button label="Success Toast" onclick={successToastFunction}></lightning-button>

        <lightning-button label="Error Toast" onclick={errorToastFunction}></lightning-button>

        <lightning-button label="Warning Toast" onclick={warningToastFunction}></lightning-button>

        <lightning-button label="Information Toast" onclick={informationToastFunction}></lightning-button>

    </lightning-card>

</template>



import { LightningElement } from 'lwc';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class TestingToastInLwc extends LightningElement {

    successToastFunction() {

        const evt = new ShowToastEvent({

            title: 'Success Message',

            message: 'Record inserted successfully ',

            variant: 'success',

            mode:'dismissible'

        });

        this.dispatchEvent(evt);

    }

    errorToastFunction() {

        const evt1 = new ShowToastEvent({

            title: 'Error Message',

            message: 'Record inserted failed ',

            variant: 'error',

            mode:'dismissible'

        });

        this.dispatchEvent(evt1);

    }

    warningToastFunction() {

        const evt2 = new ShowToastEvent({

            title: 'Warning Message',

            message: 'Some problem occured ',

            variant: 'warning',

            mode:'dismissible'

        });

        this.dispatchEvent(evt2);

    }

 

    informationToastFunction() {

        const evt3 = new ShowToastEvent({

            title: 'Information Message',

            message: 'Operation running in background ',

            variant: 'info',

            mode:'dismissible'

        });

        this.dispatchEvent(evt3);

    }

}


Add this LWC on the Home Page as shown below to test it.

Display toast notifications in Lightning Web Component




Saturday, December 25, 2021

Queueable Apex In Salesforce

 Queueable Apex in salesforce is similar to Future Method in salesforce i.e both are queued for execution however Queueable Apex provide additional benefits.

Each queued job runs when system resources become available to it. The future method always requires id's as parameter, Objects are not allowed. Objects are not allowed because there is a possibility that when future method runs i.e when resources are available to it user might have changed the data inside database which can lead to processing on wrong data where as queueable can also contains non primitives data types and it fetches data from database again before making any update thus avoiding wrong data getting inserted inside date base. 

Note: Queueable is an interface where as Future is a methodIf an Apex transaction rolls back, any queueable jobs queued for execution by the transaction are not processed.

This interface enables us to add jobs to the queue and monitor them. Using the interface is an enhanced way of running our asynchronous Apex code compared to using Future Method. Apex processes that run for a long time and includes extensive database operations or external web service callouts can be run asynchronously by implementing the Queueable interface and adding a job to the Apex job queue. In this way, our asynchronous Apex job runs in the background in its own thread and doesn’t delay the execution of our main Apex logic. Each queued job runs when system resources become available. A benefit of using the Queueable interface methods is that some governor limits are higher than for synchronous Apex, such as heap size limits.


You can visit our article on future method for more details: Future method in salesforce

Benefits of using Queueable Apex:

1) When we submit our job by invoking the System.enqueueJob method, the method returns the ID of the new job. This ID corresponds to the ID of the AsyncApexJob record. We can use this ID to identify our job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.

2) Our queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. 

3) We can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if our process depends on another process to have run first.

Let us understand the structure of queueable apex with below example,


public class QueueableApexExample implements Queueable {

    public void execute(QueueableContext context) {

        Account a = new Account(Name='Test Account Using Queueable Apex' );

        insert a;        

    }

}


Note: Queueable interface has only 1 method i.e execute method.

To add the above class as a job on the queue, 

ID jobID = System.enqueueJob(new QueueableApexExample ());

To query information about above submitted job, we can perform a SOQL query on AsyncApexJob object as shown below,

AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];

Saturday, December 4, 2021

How to make callout from batch class in salesforce?

 Yes it possible to do callouts from batch apex in salesforce. We have to implement the interface Database.AllowsCallouts in batch apex if we want to do callouts from batch apex.

Note: A single Apex transaction can make a maximum of 100 callouts to an HTTP request or an API call.

Here is an example below on how to do callouts from batch apex,


global class BatchApexCalloutClas implements Database.Batchable<sObject>,   Database.AllowsCallouts {

    public String query = 'Select ID,FirstName, LastName, Email, Name,Status__c  from Contact Where Status__c != null Limit 100;

    List<Contact> updatedConList = new List<Contact>();

    global Database.QueryLocator start(Database.BatchableContext BC) {

        return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List<Contact> conList) {      

        String endpointthirdpartysystem = 'Third Party End Point Here';      

        for ( integer i = 0; i< conList.size(); i++ ){

            try {                

                HttpRequest req = new HttpRequest();

                Http http = new Http();

                HttpResponse res = new HttpResponse();

                endpointthirdpartysystem = 'Your endpoint will be here' + '&pincode=' + conList[i].Pincode + '&country_code=1';

                req.setHeader('Authorization', header);

                req.setHeader('Content-Type', 'application/json');

                req.setEndpoint(endpointthirdpartysystem);

                req.setMethod('GET'); 

                if (!Test.isRunningTest()) {     

                    res = http.send(req);

                    if(res.getStatusCode() == 200 ){

                    String Response = res.getBody();

                    System.debug('Response is:' + res.getBody());

                    conList[i].Status__c = Response ;

                    updatedConList.add(conList[i]);

                    }

                    else{

                    conList[i].Status__c = Response ;

                    updatedConList.add(conList[i]);

                    }

                }                     

            }

            catch (Exception e) {      

                System.debug('Some error occured and is : ' + e.getMessage() + 'at line number: ' + e.getLineNumber() );        

            }

        }

    if(updatedConList.size() > 0){

     update updatedConList;

    }

    }

    global void finish(Database.BatchableContext BC){ }

}



Saturday, May 15, 2021

Database.Stateful in Batch Apex in Salesforce

 Batch Apex is stateless.  Each execution of a batch Apex job is considered a discrete transaction. If we implements Database.Stateful we can maintained state across transactions. Using Database.Stateful only instance variable holds values static members does not hold values. If we want to count records as batch proceeds maintaining state is important as after one transaction new transaction will start and members will loose their values.


Let's understand with an example,


public class UpdateContactAddresses implements

    Database.Batchable<sObject>, Database.Stateful {

 

    public Integer recordsProcessed = 0;

    public Database.QueryLocator start(Database.BatchableContext bc) {

         String query = 'SELECT Id,Name,Phone,(SELECT id,Phone from Contacts) FROM Account';

        return Database.getQueryLocator(query);

    }

    public void execute(Database.BatchableContext bc, List<Account> scope){

        // process each batch of records

        List<Contact> contacts = new List<Contact>();

        for (Account account : scope) {

            for (Contact contact : account.contacts) {

                contact.phone= account.phone;

              

                contacts.add(contact);

             

                recordsProcessed = recordsProcessed + 1;

            }

        }

        update contacts;

    }

    public void finish(Database.BatchableContext bc){

 

        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,

            JobItemsProcessed,

            TotalJobItems, CreatedBy.Email

            FROM AsyncApexJob

            WHERE Id = :bc.getJobId()];

        // call some utility to send email

          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        String[] toAddresses = new String[] {'Testabc@gmail.com'};

        mail.setToAddresses(toAddresses);

        mail.setSubject('Batch Status ' + job.Status + 'Record Processed ' + recordsProcessed );

        mail.setPlainTextBody('Total Jobs Processed: ' + job .TotalJobItems +   'with '+ job .NumberOfErrors + ' failures.');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }

}


Database.Stateful in Batch Apex in Salesforce


How to control number of batches in batch apex using scope size?

As we know default scope size is 200 i.e If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200 records.

When  an apex job is executed by setting some value for scope size it is not necessary that the number of record processed in one batch iteration will be same as that of scope size specified.

Records from the query locator are retrieved in chunks of given chunk size called retrieveChunkSize .

Chunks size available are 100,200,400.

Selection of chunk size depends on the scope size specified.


If 1 <= scopeSize <= 100, then retrieveChunkSize = 100

If 101 <= scopeSize <= 400, then retrieveChunkSize = 400
If 401 <= scopeSize <= 2000, then retrieveChunkSize = 2000


So Let say if we 285 records to be proceeds and we specify the scope size as 80 than the retrieveChunkSize  will be 100.

In this case the total number of batches will note be 4 i.e (285/80) but in this case it would be 3 retrieve chunks and 6 execute chunks so the total number of batches will be 6.

1. Retrieve chunk 1: retrieve first 100 records
Execute chunk 1: pass first 80 records to execute() method
Execute chunk 2: pass remaining 20 records from this retrieve chunk to execute() method

2. Retrieve chunk 2: retrieve next 100 records

Execute chunk 3: pass first 80 records to execute() method
Execute chunk 4: pass remaining 20 records from this retrieve chunk to execute() method

3. Retrieve chunk 3: retrieve next 85 records

Execute chunk 5: pass first 80 records to execute() method
Execute chunk 6: pass remaining 5 records from this retrieve chunk to execute() method