You need to sign in to do that
Don't have an account?
Vamshi Krishna
Issue with After update event in Trigger
When the record gets updated,it should have effect(true or false) on the other object.Please help
if (Trigger.isAfter) {
list<string> pvinUpdate = new list<string>();
list<string> pvinUpdateRemove = new list<string>();
for (Vehicle__c venNew: Trigger.new) {
Vehicle__c venOld = Trigger.oldMap.get(venNew.Id);
if(venNew.PVIN__c != venOld.PVIN__c){
pvinUpdate.add(venNew.PVIN__c);
pvinUpdateRemove.add(venNew.PVIN__c);
}
}
// if(pvinUpdate.size()>0){
list<PVIN__c> lstvenup = [SELECT Id, Name, In_Use__c FROM PVIN__c WHERE Name IN: pvinUpdate];
for(PVIN__c p : lstvenup){
p.In_Use__c = false;
}
update lstvenup;
// }
if(pvinUpdateRemove.size()>0){
list<PVIN__c> lstvenuprem = [SELECT Id, Name, In_Use__c FROM PVIN__c WHERE Name IN: pvinUpdateRemove];
for(PVIN__c pr : lstvenuprem){
pr.In_Use__c = true;
}
update lstvenuprem;
}
}
if (Trigger.isAfter) {
list<string> pvinUpdate = new list<string>();
list<string> pvinUpdateRemove = new list<string>();
for (Vehicle__c venNew: Trigger.new) {
Vehicle__c venOld = Trigger.oldMap.get(venNew.Id);
if(venNew.PVIN__c != venOld.PVIN__c){
pvinUpdate.add(venNew.PVIN__c);
pvinUpdateRemove.add(venNew.PVIN__c);
}
}
// if(pvinUpdate.size()>0){
list<PVIN__c> lstvenup = [SELECT Id, Name, In_Use__c FROM PVIN__c WHERE Name IN: pvinUpdate];
for(PVIN__c p : lstvenup){
p.In_Use__c = false;
}
update lstvenup;
// }
if(pvinUpdateRemove.size()>0){
list<PVIN__c> lstvenuprem = [SELECT Id, Name, In_Use__c FROM PVIN__c WHERE Name IN: pvinUpdateRemove];
for(PVIN__c pr : lstvenuprem){
pr.In_Use__c = true;
}
update lstvenuprem;
}
}
Your current code runs in a single thread, so it will first find all existing PVIN__c records matching the Vehicle__r.PVIN__c values, update them to In_use__c = false, then the second if conditional will find those same records, and toggle them all to true. Essentially, this means they will always be kept as true in the long run.
You should also append "FOR UPDATE" to the end of your SOQL query on the PVIN__c records since you know you will be updating them, so this enforces a record lock upon query to prevent a data desync.
What error are you getting and what is your business logic.