You need to sign in to do that
Don't have an account?
Aa Hash
trigger that only fires when field value in the custom object is changed
I have created an apex code which is populating account lookup on custom object but I want my trigger only fires when field value EXT ID__c in the custom object is changed it also create an error message on another log__c object when duplication occurs
Here is my code:
trigger Test_Account on Populate_Account__c (before insert, before update) {
set<string> externalids = new set<string>();
for(Populate_Account__c cobj:trigger.new){
if(cobj.External_ID__c != Null && cobj.Account__c==Null ){
externalids.add(cobj.External_ID__c);
}
}
Map<string,id> mapaccidswithexternalids = new Map<string,id>();
for(Account acc: [select id,External_ID__c from account where External_ID__c=:externalids]){
mapaccidswithexternalids.put(acc.External_ID__c,acc.id);
}
for(Populate_Account__c cobj:trigger.new){
if(mapaccidswithexternalids.containskey(cobj.External_ID__c)){
cobj.Account__c = mapaccidswithexternalids.get(cobj.External_ID__c);
}
}
}
Here is my code:
trigger Test_Account on Populate_Account__c (before insert, before update) {
set<string> externalids = new set<string>();
for(Populate_Account__c cobj:trigger.new){
if(cobj.External_ID__c != Null && cobj.Account__c==Null ){
externalids.add(cobj.External_ID__c);
}
}
Map<string,id> mapaccidswithexternalids = new Map<string,id>();
for(Account acc: [select id,External_ID__c from account where External_ID__c=:externalids]){
mapaccidswithexternalids.put(acc.External_ID__c,acc.id);
}
for(Populate_Account__c cobj:trigger.new){
if(mapaccidswithexternalids.containskey(cobj.External_ID__c)){
cobj.Account__c = mapaccidswithexternalids.get(cobj.External_ID__c);
}
}
}
What is the issue you were facing. ? The code seems to be fine.
If you to fire the trigger only when field changes then you need to modify the code like below.
If this helps, Please mark it as best answer.!!
Thanks!!
1. The trigger only fires when the value of field changes means EXT ID__c changes.
2.If an error occurs ,it is generated in another custom object error__c.
try with below code.
If this helps, Please mark it as best answer.
Thanks!!
instead of TypeException, you use Exception.
try with below.
If this helps, Please mark it as best answer.
Thanks!!