0

I have a trigger helper with this method:

public void changeObjects(Map<Id, Cleaning__c> oldObjectsMap, Map<Id, Cleaning__c> newObjectsMap)

But it should make changes only if FieldName__c is changed. How can I get Id for each record here to compare the values?

if(oldObjectsMap.get(someIdIsHere).FieldName__c != (newObjectsMap.get(someIdIsHere).FieldName__c){
    //our code logic
}

2 Answers 2

2

You can iterate over either key or value of the Trigger.newMap or Trigger.oldMap and in the iteration, you will get the Id of each record.

When iterating over the key using keyset() method of either of the maps that you have, you will get the Id in each iteration.

for(Id recordId : newObjectsMap.keyset()){
    if(oldObjectsMap.get(recordId).FieldName__c != (newObjectsMap.get(recordId).FieldName__c){
        //your code logic
    }
}

Similarly, if needed, you can iterate over values as well using the values() method, but in that case, you will have to access the Id from the sObject either using Dot notation or using the get method of sObject

2

As a matter of performance, you should use Trigger.old and Trigger.new instead of Trigger.oldMap and/or Trigger.newMap. You'll also get better performance by caching objects. Here's what a typical loop looks like in my triggers:

for(Integer i = 0, s = Trigger.new.size(); i < s; i++) {
  sObject oldRecord = Trigger.old[i], newRecord = Trigger.new[i];
  // do logic here //
}

This design minimizes the number of array/map accesses and method calls, and generally has the best performance characteristics, important for bulk data loads.

2
  • Yes, but I need a Map for another part of code. So, I used a Map instead of a list
    – Dan Dan
    Commented Mar 3, 2020 at 15:59
  • @DanDan both maps and lists are tools to be used appropriately. You wouldn't want to use a screwdriver when you need a hammer, nor a hammer when you need a screwdriver. I'm not saying "never use maps", just "don't use maps for this purpose."
    – sfdcfox
    Commented Mar 3, 2020 at 16:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .