You need to sign in to do that
Don't have an account?
Stefan
Code to test for field change
I am struggling to understand the basics in Apex triggers. Can anyone tell me simply how I should detect a field change. For example in the below. If the contact name has changed then I want to make some updates to the contact record.
trigger AfterUpdate on Contact (before update) {
If (Contact.Name changed)
}
}
Hi Stefan,
What you need to understand is that the context of the trigger is hold by the Trigger object and that this context can be bulk, i.e. when you insert/update massively data with the dataloader for instance. Hence, this context is not a single object, but a list of objects, or a Map.
So, in you case, you would use it in this way:
//Assign the context before and after the change into a Map Map<Id,Contact> newContactMap = Trigger.newMap; Map<Id,Contact> oldContactMap = Trigger.oldMap; //Loop through the map for(Id contactId:newMap.keySet()){ Contact myNewContact = newContactMap.get(contactId); Contact myOldContact = oldContactMap.get(contactId); if (myNewContact.Name<> myOldContact.Name){ //Here goes your processing } }
All Answers
Hi Stefan,
What you need to understand is that the context of the trigger is hold by the Trigger object and that this context can be bulk, i.e. when you insert/update massively data with the dataloader for instance. Hence, this context is not a single object, but a list of objects, or a Map.
So, in you case, you would use it in this way:
//Assign the context before and after the change into a Map Map<Id,Contact> newContactMap = Trigger.newMap; Map<Id,Contact> oldContactMap = Trigger.oldMap; //Loop through the map for(Id contactId:newMap.keySet()){ Contact myNewContact = newContactMap.get(contactId); Contact myOldContact = oldContactMap.get(contactId); if (myNewContact.Name<> myOldContact.Name){ //Here goes your processing } }
Hi Sebastion, I think there is a syntax error in your code which I am unable to figure out.
I am getting this error when tryng to save:
trigger updateDemo on Contact (before update) { //Assign the context before and after the change into a Map Map<Id,Contact> newContactMap = Trigger.newMap; Map<Id,Contact> oldContactMap = Trigger.oldMap; //Loop through the map for(Id contactId:newMap.keySet()){ Contact myNewContact = newContactMap.get(contactId); Contact myOldContact = oldContactMap.get(contactId); if (myNewContact.Name<> myOldContact.Name){ //Here goes your processing } } }
Hi,
Yeah, inddeed, I wrote this out of the blue ....
You need to replace:
for(Id contactId:newMap.keySet()){
with
for(Id contactId:newContactMap.keySet()){