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) {





                recordsProcessed = recordsProcessed + 1;



        update contacts;


    public void finish(Database.BatchableContext bc){


        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,


            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[] {''};


        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

What is Batch Apex In Salesforce?

 When we want to deal with large number of records we go for batch apex. The code inside batch class runs asynchronously i.e in future context. The governor limit are also more as compared to synchronous code. 

When we use batch apex we implements Database.batchable() interface and we have to include three methods and they are as follows:


Start method and finish method are called only once inside batch class. 

  • Start method collects the data for processing. 
  • Execute method performs operations. 
  • The order of execution is not guaranteed in execute method.
  • Finish method generally used for sending emails or calling another batch class when the current batch is completed. 


global class batch implements Database.Batchable < sObject > { 

global (Database.QueryLocator or  Iterable<sObject>)

start(Database.BatchableContext bc) { 

//query on object; 

//return Database.getQueryLocator(query); 

global void execute(Database.batchableContext bc, List < SObject > scope) { 

//some processing. 

global void finish(Database.BatchableContext bc) { 

//job such as sending email or calling another batch class 

Sunday, March 14, 2021

How to use getObjectInfo in Lightning Web Component?

 In this blog post we will learn how to use getObjectInfo in Lightning Web Component.

Let us take a simple example to understand the use of getObjectInfo in Lightning Web Component.



  <p>Object Info Component</p> 



import { LightningElement, wire } from 'lwc';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';

import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class ObjectInfoComp extends LightningElement {

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })

    wiredData({data, error}){


         console.log('Object INFO:', data);



         console.log('Some Error Occured');






<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="">








Now, Add the component on account record lightning page as shown below,

getObjectInfo in Lightning Web Component

Open the console and we will be able to see all different information related to the object as shown below.

How to use getObjectInfo in Lightning Web Component?

Tuesday, March 9, 2021

What are data types in Javascript?

 A) Values in Javascript will have a type.

B) There are 8 basic data types in Javascript.

1) String

let name = 'Test';  

String in Javscript is surrounded by quotes. 

Quotes can single, double quotes.

2) Number

let n = 10;  // Number

3) Boolean

let checkName =  true;

let checkData = false;

4) "null" 

It contains only null value. 

In Javascript, null is not a reference to a non existing object or null pointer. 

It just represents empty or unknown value.

let a= null;

5) "undefined"

It also represent special type, here the variable is declared but not assigned any value as shown below,

let a;

6) bigint

Used to store integers value of arbitrary length.

bigint value is created by appending n to the end of an integer.

const = 11111111112222222223333333333344444444n;

7) object

a) object are used to store collections of data and more complex entities.

b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.

c) Creating an empty object,

let studentDetail = {};

let steudentDetail = new Object();

d) Creating an object with properties,

let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"


e) To access the property values use dot notation or array notation in case of space in key name as shown below,  // dot notation

To access full name use array notation as it has space.

studentDetail[Full Name]   // array notation

f) Adding a value to property,

studentDetail.department = 'Computer Science';

g) We may add comma to last property as shown below.

let studentDetail = {

name: "Test",

rollNo: 1,


h) To access the keys use,


i) Use JSON.stringify to convert object to string

var jsonStrng= JSON.stringify(studentDetail);


"{"name":"Test","rollNo":1,"Full Name":"Test User"}"

j) Use JSON.parse to convert string to object

Object = JSON.parse(jsonStrng);

{name: "Test", rollNo: 1, Full Name: "Test User"}

k) The below are also different kinds of object in Javascript,




8) symbol