How to Add a Dynamic Child List to Parent in Apex Class || Trigger using map
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 existing list
parentIdAndChildRecordsMap.get(childRecord.parentId__c).add(childRecord);
} else {
// Parent ID not found in the map
// Create a new entry in the map with the parent ID and a list containing the child record
parentIdAndChildRecordsMap.put(
childRecord.parentId__c,
new List<object>{childRecord}
);
}
}
Explanation
- Map Definition: Map<Id, List<Object>> parentIdAndChildRecordsMap = new Map<Id, List<Object>>(); This line declares a map (parentIdAndChildRecordsMap) where keys are of type Id (presumably representing parent record IDs), and values are lists of type Object (presumably representing child records).
- Loop Through Trigger Context: for (Object childRecord : Trigger) {: This loop iterates through each object in the Trigger context. The Trigger context typically holds records that caused the trigger to execute.
- Check if Parent ID Exists in Map: if (parentIdAndChildRecordsMap.containsKey(childRecord.parentId__c)) {: Checks whether the map already contains the parent ID of the current childRecord.
- Add Child Record to Existing List: parentIdAndChildRecordsMap.get(childRecord.parentId__c).add(childRecord);: If the parent ID is already in the map, it retrieves the associated list of child records and adds the current childRecord to that list.
- Create New Map Entry if Parent ID Not Found: parentIdAndChildRecordsMap.put(childRecord.parentId__c, new List<Object>{childRecord});: If the parent ID is not found in the map, it creates a new entry in the map with the parent ID and a list containing the current childRecord.
Comments
Post a Comment