Posts

Showing posts from January, 2024

How to Add a Dynamic Child List to Parent in Apex Class || Trigger using map

Last Updated: 13-01-2024 Map<parentId, List<child>>  Code without comments Map<id, List<object>> parentIdAndChildRecordsMap = new Map<id, List<object>>(); for(object childRecord : Trigger) { if(parentIdAndChildRecordsMap.containsKey(childRecord.parentId__c)) { parentIdAndChildRecordsMap.get(childRecord.parentId__c).add(childRecord); } else { parentIdAndChildRecordsMap.put( childRecord.parentId__c, new List<object>{childRecord} ); } } Code with comments // Define a map to store parent IDs and their associated child records Map<id, List<object>> parentIdAndChildRecordsMap = new Map<id, List<object>>(); // Iterate through each object in the Trigger context (likely a trigger context variable) for(object childRecord : Trigger) { // Check if the map already contains the parent ID if(parentIdAndChildRecordsMap.containsKey(childRecord.parentId__c)) { // Parent ID found, so add the child record to the existin