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());
        }
    }
}