Back to Top

Custom Notifications in Salesforce

Posted on TimeApril 9, 2026

Custom Notifications alert users about important events in Salesforce.

Configured by selecting supported channels (desktop/mobile).

Send using Flow, Apex.


Use Cases:


Lead Assignment Notification

Case Escalation Alert

Approval Request Notification

Task Reminder

Opportunity Stage Change

Record ownership Change


Creating Notification Types:

Go to quick find in setup and search custom notifications
Create notification types in Setup and choose desktop/mobile channels.


Send custom notifications:
Sending Notifications with Flow
Record-Triggered Flows can send notifications when records are created or updated.
Using Apex
Developers can send notifications programmatically using Messaging.CustomNotification class.


 private static void sendNotification(String name, Id targetId, Id ownerId) {
    //     if (ownerId != null) {
    //         Messaging.CustomNotification notification = new Messaging.CustomNotification();
    //         notification.setBody(name + ' is now waiting for Review.');
    //         notification.setTitle('Notification Alert');
    //         notification.setSenderId(Userinfo.getUserId());
    //         CustomNotificationType type = [SELECT Id FROM CustomNotificationType WHERE DeveloperName = 'IA_Status_Change_Notifications'];
    //         notification.setNotificationTypeId(type.id);
    //         notification.setTargetId(targetId);
    //         notification.send(new Set<String> { ownerId });
    //     }
    // }

In Flow - 1. Get Custom Notification Type - Record
2. Set User Id in set variable.
3. Send using action.

Portal User Self-Registration

Apex:  


global without sharing class RIDOSSelfRegistrationController implements Callable {

    public String PORTAL_PROFILE_NAME;
    public String PERSON_ACCOUNT_RECORDTYPE_NAME;

    global Boolean invokeMethod(String methodName, Map<String, Object> inputMap, Map<String, Object> outMap, Map<String, Object> options) {
        if (methodName == 'saveDetails') {
            saveDetails(inputMap, outMap);
        } else if (methodName == 'fetchExsistingUsername') {
            fetchExsistingUsername(inputMap, outMap);
        }
        return true;
    }

    public Object call(String action, Map<String, Object> args) {
        Map<String, Object> input = (Map<String, Object>) args.get('input');
        Map<String, Object> output = (Map<String, Object>) args.get('output');
        Map<String, Object> options = (Map<String, Object>) args.get('options');

        return invokeMethod(action, input, output, options);
    }

    global void saveDetails(Map<String, Object> inputMap, Map<String, Object> outMap) {
        try {
            String communityName = 's';
            Map<String, Object> metadataInfo = getMetadataForCommunity(communityName);
            PORTAL_PROFILE_NAME = (String) metadataInfo.get('profileName');
            PERSON_ACCOUNT_RECORDTYPE_NAME = (String) metadataInfo.get('perAccRecTypeDevName');

            if (String.isBlank(PORTAL_PROFILE_NAME)) {
                outMap.put('showError', 'Please contact your administrator.');
                return;
            }

            String personAccRecordTypeId =
                Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName()
                    .get(PERSON_ACCOUNT_RECORDTYPE_NAME)
                    .getRecordTypeId();

            Map<String, Object> selfRegStep = (Map<String, Object>) inputMap.get('SelfRegStep');

            String firstName = !String.isBlank(String.valueOf(selfRegStep.get('firstName')))
                ? String.valueOf(selfRegStep.get('firstName')) : null;
            String firstNameCapitalize = !String.isBlank(firstName) ? capitalizeName(firstName) : null;

            String lastName = !String.isBlank(String.valueOf(selfRegStep.get('lastName')))
                ? String.valueOf(selfRegStep.get('lastName')) : null;
            String lastNameCapitalize = !String.isBlank(lastName) ? capitalizeName(lastName) : null;

            String email = (String) selfRegStep.get('useremail');
            String rawUsername = selfRegStep != null ? String.valueOf(selfRegStep.get('UsernameWithouEmail')) : null;
            rawUsername = normalizeUsername(rawUsername);

            if (String.isBlank(rawUsername)) {
                outMap.put('showError', 'Username is required.');
                return;
            }

            if (rawUsername.contains(' ')) {
                outMap.put('showError', 'Username should not contain spaces.');
                return;
            }

            String finalUsername = buildUsernameWithDomain(rawUsername);

            List<User> users = [
                SELECT Id
                FROM User
                WHERE Username = :finalUsername
                   OR Email = :email
                LIMIT 1
            ];

            List<Account> existingAcc = [
                SELECT Id
                FROM Account
                WHERE User_Name__c = :rawUsername
                LIMIT 1
            ];

            if (!users.isEmpty() || !existingAcc.isEmpty()) {
                outMap.put('showError', 'An user with the entered username or email already exists.');
                return;
            }

            String middleName = !String.isBlank(String.valueOf(selfRegStep.get('middleName')))
                ? String.valueOf(selfRegStep.get('middleName')) : null;
            String middleNameCapitalize = !String.isBlank(middleName) ? capitalizeName(middleName) : null;

            Account acc = new Account();
            acc.FirstName = firstNameCapitalize;
            acc.LastName = lastNameCapitalize;
            acc.MiddleName = middleNameCapitalize;
            acc.PersonEmail = email;
            // acc.User_Name__c = finalUsername;
            acc.User_Name__c = rawUsername;
            acc.Phone = !String.isBlank(String.valueOf(selfRegStep.get('phoneNumber')))
                ? String.valueOf(selfRegStep.get('phoneNumber')) : null;
            acc.RecordTypeId = personAccRecordTypeId;
            acc.User_Type__c = !String.isBlank(String.valueOf(selfRegStep.get('UserType')))
                ? String.valueOf(selfRegStep.get('UserType')) : null;

            List<Site> classSite = [
                SELECT Id, Name, GuestRecordDefaultOwnerId, GuestRecordDefaultOwner.Name
                FROM Site
                WHERE Name = 'Department_of_State'
                LIMIT 1
            ];
            if (!classSite.isEmpty()) {
                acc.OwnerId = classSite[0].GuestRecordDefaultOwnerId;
            }

            List<Account> accounts = [
                SELECT Id, User_Name__c
                FROM Account
                WHERE
                FirstName = :acc.FirstName
                  AND LastName = :acc.LastName
                  AND PersonEmail = :email
                  AND RecordTypeId = :personAccRecordTypeId
                LIMIT 1
            ];

            if (!accounts.isEmpty()) {
                createUser(accounts[0].Id, rawUsername);
                if (accounts[0].User_Name__c == null){
                    accounts[0].User_Name__c = rawUsername;
                    update accounts;
                }
                outMap.put('showError', '');
            } else {
                Database.DMLOptions dml = new Database.DMLOptions();
                dml.DuplicateRuleHeader.allowSave = true;
                Database.insert(acc, dml);
                createUser(acc.Id, rawUsername);
                outMap.put('showError', '');
            }

        } catch (Exception e) {
            logException(e, 'saveDetails');
            throw e;
        }
    }

    global void fetchExsistingUsername(Map<String, Object> inputMap, Map<String, Object> outMap) {
        try {
            Map<String, Object> selfRegStep = (Map<String, Object>) inputMap.get('SelfRegStep');
            String rawUsername = selfRegStep != null ? String.valueOf(selfRegStep.get('UsernameWithouEmail')) : null;
            // String email = selfRegStep != null ? String.valueOf(selfRegStep.get('UsernameWithouEmail')) : null;
            String email = selfRegStep != null ? (String) selfRegStep.get('useremail'): null;
            rawUsername = normalizeUsername(rawUsername);

            Boolean isExisting = false;
            String message = '';
            String messageType = '';

            if (String.isBlank(rawUsername)) {
                outMap.put('SelfRegSameUsername', true);
                outMap.put('usernameMessage', 'Username is required');
                outMap.put('usernameMessageType', 'error');
                return;
            }

            if (rawUsername.contains(' ')) {
                outMap.put('SelfRegSameUsername', true);
                outMap.put('usernameMessage', 'Username should not contain spaces');
                outMap.put('usernameMessageType', 'error');
                return;
            }

            String finalUsername = buildUsernameWithDomain(rawUsername);

            List<User> userList = [
                SELECT Id
                FROM User
                WHERE Username = :finalUsername
                OR Email = :email
                LIMIT 1
            ];

            List<Account> accList = [
                SELECT Id
                FROM Account
                WHERE User_Name__c = :rawUsername
                LIMIT 1
            ];

            isExisting = !userList.isEmpty() || !accList.isEmpty();

            if (isExisting) {
                message = 'Username or email already present in the system.';
                messageType = 'error';
            } else {
                message = 'Username is available.';
                messageType = 'success';
            }

            outMap.put('SelfRegSameUsername', isExisting);
            outMap.put('usernameMessage', message);
            outMap.put('usernameMessageType', messageType);

        } catch (Exception e) {
            logException(e, 'fetchExsistingUsername');
            throw e;
        }
    }

    private static String normalizeUsername(String username) {
        return String.isBlank(username) ? null : username.trim();
    }

    private static String buildUsernameWithDomain(String rawUsername) {
        return rawUsername + System.Label.RIDOSEmail;
    }

    private Map<String, Object> getMetadataForCommunity(String communityName) {
        try {
            Map<String, Object> metadataInfo = new Map<String, Object>();
            Map<String, Portal_Configuration__mdt> metadataRecords = Portal_Configuration__mdt.getAll();

            for (Portal_Configuration__mdt record : metadataRecords.values()) {
                if (record.Site_Name__c == communityName) {
                    metadataInfo.put('profileName', record.Profile_Name__c);
                    metadataInfo.put('perAccRecTypeDevName', record.Person_Account_Record_Type_DeveloperName__c);
                    break;
                }
            }
            return metadataInfo;
        } catch (Exception e) {
            logException(e, 'getMetadataForCommunity');
            throw e;
        }
    }

    public static String capitalizeName(String inputName) {
        String properCaseName = '';

        if (String.isNotBlank(inputName)) {
            String[] nameParts = inputName.split(' ');
            for (String namePart : nameParts) {
                properCaseName += namePart.substring(0, 1).toUpperCase() +
                                  namePart.substring(1).toLowerCase() + ' ';
            }
            properCaseName = properCaseName.trim();
        }
        return properCaseName;
    }

    @future
    public static void createUser(Id accountId, String rawUsername) {
        try {
            List<Account> accList = [
                SELECT Id, FirstName, LastName, PersonEmail, Phone, PersonContactId, User_Name__c
                FROM Account
                WHERE Id = :accountId
            ];

            if (!accList.isEmpty()) {
                Profile p = [SELECT Id, Name FROM Profile WHERE Name = 'RIDOS Portal User' LIMIT 1];
                Account acc = accList[0];

                User u = new User();
                u.FirstName = acc.FirstName;
                u.LastName = acc.LastName;
                u.Email = acc.PersonEmail;
                u.Phone = acc.Phone;
                u.ProfileId = p.Id;
                // u.Username = acc.User_Name__c;
                u.Username = rawUsername + System.Label.RIDOSEmail;
                u.IsActive = true;
                u.TimeZoneSidKey = 'America/New_York';
                u.LocaleSidKey = 'en_US';
                u.LanguageLocaleKey = 'en_US';
                u.EmailEncodingKey = 'UTF-8';
                u.ContactId = acc.PersonContactId;
                u.Alias = (acc.FirstName != null ? acc.FirstName.substring(0, 1) : 'x') +
                          acc.LastName.substring(0, 1);

                Database.DMLOptions dmo = new Database.DMLOptions();
                dmo.EmailHeader.triggerUserEmail = true;
                dmo.EmailHeader.triggerOtherEmail = true;
                dmo.EmailHeader.triggerAutoResponseEmail = true;
                dmo.optAllOrNone = false;
                u.setOptions(dmo);

                insert u;
            }
        } catch (Exception e) {
            logException(e, 'createUser');
            throw e;
        }
    }

    public static void logException(Exception e, String methodName) {
        try {
            User currentUser = [
                SELECT FirstName, LastName, Email, Username
                FROM User
                WHERE Id = :UserInfo.getUserId()
            ];

            String siteId = Site.getSiteId();

            RIDOS_Exception__c errorInsert = new RIDOS_Exception__c();
            errorInsert.FirstName__c = currentUser.FirstName;
            errorInsert.LastName__c = currentUser.LastName;
            errorInsert.Email__c = currentUser.Email;
            errorInsert.UserName__c = currentUser.Username;

            String errorMessage =
                'Apex class: RIDOSSelfRegistrationController\nMethod Name: ' + methodName +
                '\nError Line Number: ' + e.getLineNumber() +
                '\nError Message: ' + e.getMessage();

            errorInsert.Exception__c = errorMessage;
            errorInsert.NetworkId__c = siteId;

            insert errorInsert;
        } catch (Exception ex) {
            System.debug('Exception while logging exception: ' + ex.getMessage());
        }
    }
}

Custom Login Component

Posted on TimeMarch 30, 2026

 Apex:

public without sharing class RIDOSCustomLoginController {

    @AuraEnabled
    public static String loginUser(String usernameInput, String password, String startUrl) {
        if (String.isBlank(usernameInput)) {
            throw new AuraHandledException('Username is required.');
        }
        if (String.isBlank(password)) {
            throw new AuraHandledException('Password is required.');
        }

        String finalUsername = usernameInput.trim();

        if (finalUsername.contains(' ')) {
            throw new AuraHandledException('Username should not contain spaces.');
        }

        if (!finalUsername.contains('@')) {
            finalUsername = finalUsername + System.Label.RIDOSEmail;
        }

        String targetUrl = String.isBlank(startUrl) ? '/s/' : startUrl;

        try {
            PageReference loginResult = Site.login(finalUsername, password, targetUrl);

            if (loginResult != null) {
                return loginResult.getUrl();
            }

            throw new AuraHandledException('Your login attempt has failed. Make sure the username and password are correct.');
        } catch (Exception e) {
            throw new AuraHandledException('Your login attempt has failed. Make sure the username and password are correct.');
        }
    }
}

LWC: Js:
import { LightningElement, track } from 'lwc';
import loginUser from '@salesforce/apex/RIDOSCustomLoginController.loginUser';

export default class RidosCustomLoginPage extends LightningElement {
    @track username = '';
    @track password = '';
    @track errorMessage = '';
    @track isLoading = false;

    get buttonLabel() {
        return this.isLoading ? 'Logging in...' : 'Log in';
    }

    handleUsernameChange(event) {
        this.username = event.target.value;
        this.errorMessage = '';
    }

    handlePasswordChange(event) {
        this.password = event.target.value;
        this.errorMessage = '';
    }

    async handleLogin() {
        this.errorMessage = '';

        const trimmedUsername = this.username ? this.username.trim() : '';

        if (!trimmedUsername) {
            this.errorMessage = 'Username is required.';
            return;
        }

        if (trimmedUsername.includes(' ')) {
            this.errorMessage = 'Username should not contain spaces.';
            return;
        }

        if (!this.password) {
            this.errorMessage = 'Password is required.';
            return;
        }

        this.isLoading = true;

        try {
            const redirectUrl = await loginUser({
                usernameInput: trimmedUsername,
                password: this.password,
                startUrl: '/s/'
            });

            window.location.href = redirectUrl;
        } catch (error) {
            this.errorMessage =
                error && error.body && error.body.message
                    ? error.body.message
                    : 'Invalid username or password.';
        } finally {
            this.isLoading = false;
        }
    }
}


Html:

<template>
    <div class="login-wrapper">

        <!-- 🔴 Error message on top -->
        <template if:true={errorMessage}>
            <div class="error-message-top">
                {errorMessage}
            </div>
        </template>

        <!-- Username -->
        <div class="input-box">
            <lightning-icon
                icon-name="utility:user"
                size="x-small"
                alternative-text="Username"
                class="input-icon">
            </lightning-icon>

            <input
                class="custom-input"
                type="text"
                placeholder="Username"
                value={username}
                oninput={handleUsernameChange} />
        </div>

        <!-- Password -->
        <div class="input-box">
            <lightning-icon
                icon-name="utility:lock"
                size="x-small"
                alternative-text="Password"
                class="input-icon">
            </lightning-icon>

            <input
                class="custom-input"
                type="password"
                placeholder="Password"
                value={password}
                oninput={handlePasswordChange} />
        </div>

        <!-- Button -->
        <button class="login-btn" onclick={handleLogin} disabled={isLoading}>
            {buttonLabel}
        </button>

    </div>
</template>


CSS:

.login-wrapper {
    width: 100%;
    max-width: 640px;
    margin: 0 auto;
    padding: 1rem 0;
}

.input-box {
    display: flex;
    align-items: center;
    height: 60px;
    border: 1px solid #c9c9c9;
    border-radius: 4px;
    background: #ffffff;
    margin-bottom: 22px;
    padding: 0 16px;
    box-sizing: border-box;
}

.input-icon {
    margin-right: 12px;
    --sds-c-icon-color-foreground-default: #000000;
    flex-shrink: 0;
}

.custom-input {
    border: none;
    outline: none;
    width: 100%;
    font-size: 1.1rem;
    color: #8b8b8b;
    background: transparent;
}

.custom-input::placeholder {
    color: #8b8b8b;
    opacity: 1;
}

.login-btn {
    width: 100%;
    height: 58px;
    border: none;
    border-radius: 4px;
    background: #002f5f;
    color: #ffffff;
    font-size: 1.2rem;
    font-weight: 700;
    cursor: pointer;
}

.login-btn:hover {
    background: #002a54;
}

.login-btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.error-message {
    margin-top: -8px;
    margin-bottom: 16px;
    color: #c23934;
    font-size: 0.95rem;
}

.error-message-top {
    margin-bottom: 16px;
    padding: 10px;
    background: #fdecea;
    border: 1px solid #f5c6cb;
    color: #c23934;
    border-radius: 4px;
}


Important Operator

Posted on TimeMarch 6, 2026

 Nullish coalescing operator


-> The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side 

operand is null or undefined, and otherwise returns its left-hand side operand.

## Syntaxt: leftExpr ?? rightExpr


Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing#assigning_a_default_value_to_a_variable



###Nullish coalescing assignment (??=)


-> The nullish coalescing assignment (??=) operator, also known as the logical nullish assignment operator, 

only evaluates the right operand and assigns to the left if the left operand is nullish (null or undefined).


## Syntaxt: x ??= y


-> Exmaple: 


const a = { duration: 50 };


a.duration ??= 10;

console.log(a.duration);

// Expected output: 50


a.speed ??= 25;

console.log(a.speed);

// Expected output: 25


Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment


Optional chaining (.)

-> The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator 

is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.


### Syntax: 


obj.val?.prop

obj.val?.[expr]

obj.func?.(args)



Example:


const adventurer = {

  name: 'Alice',

  cat: {

    name: 'Dinah',

  },

};


const dogName = adventurer.dog?.name;

console.log(dogName);

// Expected output: undefined


console.log(adventurer.someNonExistentMethod?.());

// Expected output: undefined



### Description: The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), 

the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.


###

By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure obj.first is not null or undefined 

before attempting to access obj.first.second. If obj.first is null or undefined, the expression automatically short-circuits, returning undefined.

const nestedProp = obj.first?.second;


Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining



Ternary Operator 

###Syntax:    condition ? exprIfTrue : exprIfFalse


###Description: Besides false, possible falsy expressions are: null, NaN, 0, the empty string (""), and undefined. 

If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse.


### Conditional chains: 


The ternary operator is right-associative, which means it can be "chained" in the following way, 

similar to an if … else if … else if … else chain:


function example() {

  return condition1 ? value1

    : condition2 ? value2

    : condition3 ? value3

    : value4;

}


Documentations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator


GitHub learning

 1. The local and remote repositories only interact when you run one of the four network commands in Git: git clone, git fetch, git pull, and git push.

2. You can't create commits without these settings, so set them yourself using your command line application:


   git config --global user.name "First Last"

   and then enter,

   git config --global user.email "you@email.com"

   

  Note: You won't see any confirmation that this worked, but as long as you don't see an error, you're set!



3. Configure autocrlf

   Next, we set core.autocrlf (autocrlf stands for auto carriage return line feed). Different systems handle line endings and line breaks differently. If you open a file created on another operating system and do not have this config option set, Git will think you made changes to the file based on the way your operating system handles the line endings.


   For Windows users enter:


   git config --global core.autocrlf true


4. git checkout myfeaturebranch for swith into myfeaturebranch.

5. Let’s take another look at our repository status: git status.



IMPORTANT =>


1. first checkout (switch branch) 2. git pull (for retrive) 3. git merge origin/RBKQA (for merge all files in current branch) 4. make changes

5. staged your changes 6. commit & push. 


Done! 


Additional - 


git reset --merge => Abort the merge and return to the previous state.


Note: 


1. Sometime if you are not using correct feature branch then it will give you error. for merging 

Test Class | Test Apex Related Interview Questions


Why we test-> To save time, to become better at our craft, and to build better software.


Why we create test data-> Naturally, the data in your production org changes over time and will be different from the data in your developer environment. 

When your tests run, either in a developer environment or in production, they have access only to the data in that org. 

So if you write tests using existing data, you can end up with deployment problems, because the data available in one environment isn’t always available in another environment.


->  Test.startTest() and Test.stopTest() => Any code between those two calls executes with a refreshed set of governor limits.


Create data-> 3 methods-> TestFactory class, @TestSetup & csv file.


Apex is by default with sharing or without sharing?

 By default, Apex classes are without sharing, meaning they run in "system context" and ignore the current user’s record-level sharing rules, permissions, and field-level security. They have full access to all data, although they still respect organization-wide defaults.


Key Details regarding Default Behavior:


  • Without Sharing (Default): If neither with sharing nor without sharing is declared, the class runs in system mode, ignoring user sharing rules.
  • Inheritance: If an undeclared class is called by a with sharing class, it inherits that strict context.
  • Triggers: Triggers are also without sharing by default, running in system context.
  • Security Risk: Because the default is insecure, it is highly recommended to explicitly declare with sharing to enforce security rules.
  • AuraEnabled: @AuraEnabled classes can sometimes behave differently, but generally, they follow the same rules, necessitating explicit declaration.

Salesforce Developer Interview Questions

Posted on TimeJanuary 7, 2026

 Q:1 Asynchronus Apex

Ans: If we have to run some job that will take some time then in the case of synchronous apex we will get the limit error, heap size error, or timeout error. To avoid such issues, we can do those long-running or time-consuming operations using Asynchronous apex which will run in a separate thread and will not impact the main thread. So Asynchronous Apex is used to run the process in a separate thread at a later time.

Increase User Efficiency
More Heap Size and Higher Governer limit
Better Scalability

Batch Apex
Future methods
Queueable Apex
Scheduled Apex

Q.2 Where we can use Asynchronous Apex?
Sending Email to the user.
Calling an external system for multiple records
Schedule a job for a specific time
Chaining apex code execution which might use

Q. 3 Can a future method call another non-future method to process tasks like callouts, and have those methods return data to the future method for further processing?

No, we can not call future methods from the future method.

Q:4 How many Schedulable Apex jobs can you have at one time? In other words, what is the maximum number of Apex classes that can be scheduled concurrently?
100

Q:5  Why sObject parameters not supported in future methods?
The sObject might change between the time we call the method and the time it executes that’s why sObjects can’t be passed as arguments to future methods. In this case, the future method will get the old sObject values and might overwrite them.

Q:6  Can I call Queueable from a batch?
Yes, But it is limited to just one System.enqueueJob call per execute in the  Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.

Q:7 How Future method helps in avoiding Mixed DML errors?

There are 2 kinds of sObjects in salesforce.
1. Non-Setup: Account, opportunity, etc
2. Setup: User, groups,Queue etc
If we are performing DML on both kinds of sObject in a single transaction, the system doesn’t allow it and throws an exception called Mixed DML exception, stating that a transaction can not have a Mixture of DML operation(Setup and Non-Setup).

Q.8 What is Database.QueryLocator & Iterable<sObject>?

In Database.QueryLocator, we use a simple query (SELECT) to generate the scope of objects. The governor limit for the total number of records retrieved by SOQL queries is bypassed, i.e. it can return up to 50 million records.

In Iterable<sObject>, we can create a custom scope for processing, which would be not possible to create using SOQL where clauses. the governor limit for the total number of records retrieved by SOQL queries is still enforced.


In Salesforce, each Account can have multiple Opportunities associated with it. We need to calculate and store the Total Closed-Won Opportunity Amount for each Account in a custom field called Total_Closed_Won_Amount__c

This field should be updated whenever any Opportunity is:

  1. Inserted (new Opportunity created)
  2. Updated (Stage changes to or from "Closed Won", or the Amount changes)
  3. Deleted (Opportunity is deleted)
  4. Undeleted (Opportunity is restored from the Recycle Bin)

trigger OpportunityTrigger on Opportunity (
    after insert, after update, after delete, after undelete
) {
    if (Trigger.isAfter) {
        OpportunityTriggerHandler.updateAccountTotals(
            Trigger.new,
            Trigger.oldMap
        );
    }
}


public class OpportunityTriggerHandler {

    public static void updateAccountTotals(
        List<Opportunity> newList,
        Map<Id, Opportunity> oldMap
    ) {
        Set<Id> accountIds = new Set<Id>();

        if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
            for (Opportunity opp : newList) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (Trigger.isUpdate || Trigger.isDelete) {
            for (Opportunity opp : oldMap.values()) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (accountIds.isEmpty()) return;

        // 🔥 Aggregate Query
        Map<Id, Decimal> accountToTotalMap = new Map<Id, Decimal>();

        for (AggregateResult ar : [
            SELECT AccountId accId, SUM(Amount) totalAmount
            FROM Opportunity
            WHERE AccountId IN :accountIds
            AND StageName = 'Closed Won'
            GROUP BY AccountId
        ]) {
            accountToTotalMap.put(
                (Id) ar.get('accId'),
                (Decimal) ar.get('totalAmount')
            );
        }

        List<Account> accountsToUpdate = new List<Account>();

        for (Id accId : accountIds) {
            accountsToUpdate.add(new Account(
                Id = accId,
                Total_Closed_Won_Amount__c =
                    accountToTotalMap.containsKey(accId)
                    ? accountToTotalMap.get(accId)
                    : 0
            ));
        }

        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }
}


Other Common Trigger Scenarios Using Aggregate Query


Count of Contacts on Account:
    
SELECT AccountId, COUNT(Id)
FROM Contact
GROUP BY AccountId


Average Case Resolution Time per Account

SELECT AccountId, AVG(Resolution_Time__c)
FROM Case
GROUP BY AccountId

Total Order Amount on Customer:

SELECT Customer__c, SUM(Order_Amount__c)
FROM Order__c
GROUP BY Customer__c

Can we use if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) in handler?

Ans: If your handler method is called directly from a trigger, then the Trigger context variables are still available inside the handler.

It will NOT work if:

  • The handler is called from:

    • Batch Apex

    • Queueable

    • Future method

    • Anonymous Apex

    • Unit test calling the handler directly

Can we use Trigger.isInsert inside a handler class?

Ans: Yes, technically it works if the handler is invoked from a trigger.
However, for testability, reusability, and clean architecture, it’s best practice to pass the trigger context explicitly instead of relying on Trigger.isInsert inside the handler.