I have recently begun to understand the value of Maps when writing Apex triggers and classes, they can be very powerful. The most common Map used is the 'Map <ID, sObject>' this means that the Key of the Map is the ID and the value is the object related to the ID.
Typically you will see it initiated in this way:
Map<ID,sObject> sObMap = new Map<ID,sObject>([SELECT *fields* FROM sObject WHERE *conditions*]);
This is how I used it in a recent bit of code I wrote. This trigger copies the owner of the Account related to a case down to the case record on a custom field.
trigger CaseBeforeInsertTrigger on Case (before insert) {
Set<Id> accountIds = new Set<Id>(); //set to hold list of Accounts
for (Case c : Trigger.new) { //loop through all cases and pull the Account ID into the set above
if(c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<ID, Account> acct = new Map<ID, Account>([select id, ownerid from Account where id = : AccountIds]); //create a map where the ID is the Key and the Value is the sObject (Account)
if(acct.size() > 0) {
for(Case c: Trigger.new) { //if there are values in the map, loop through the new cases
if (c.AccountId != null){
Account acctUpdate= acct.get(c.AccountID); //look back into the map and using the Account ID grab the Account sObject
c.Account_Owner__c = acctUpdate.OwnerId;
}
}
}
}
No comments:
Post a Comment