Sunday, January 21, 2024

Apex: Get List of SObject records by Ids

The getSobjectListById() method is a powerful utility function that can greatly simplify the task of grouping SObject records by a specific field. By improving code performance and readability, this method can help you write more efficient and maintainable Apex code.

public static Map<Id, List<SObject>> getSobjectListById(String key, List<SObject> incomingList) {
    Map<Id, List<SObject>> returnValues = new Map<Id, List<SObject>>();
    for (SObject current : incomingList) {
        if (current.get(key) != null) {
            Id currentId = (Id) current.get(key);
            if (!returnValues.containsKey(currentId)) {
                returnValues.put(currentId, new List<SObject>());
            }
            returnValues.get(currentId).add(current);
        }
    }
    return returnValues;
}

This utility function takes a field name (key) and a list of SObject records as parameters. It returns a map where the keys are the unique IDs from the specified field, and the values are lists of SObject records that have the same field value.

Let's consider a real-life scenario where getSobjectListById() can be used. Suppose you are working on a Salesforce project where you need to send a customized email to each Account's Contacts. The email content is based on the specific Account's details.

First, you would query all the Contacts and their related Account details. Then, you would need to group these Contacts based on their AccountId. This is where getSobjectListById() comes into play. You can use this method to create a map where the key is the AccountId and the value is a list of Contacts related to that Account.

Here's how you can do it:

List<Contact> contactList = [SELECT Id, Name, AccountId, Account.Name FROM Contact];
Map<Id, List<SObject>> accountContactsMap = Utils.getSobjectListById('AccountId', contactList);

Now, accountContactsMap contains a list of Contacts for each AccountId. You can iterate over this map to send a customized email to each Account's Contacts.

Share This:    Facebook Twitter

0 comments:

Post a Comment

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top