
trigger quantityleft on Sample_Transaction__c (after insert,after update,after delete,after undelete) {
List<Sample_Lot__c> list_Account= new List<Sample_Lot__c>();
set<Id> set_Opportunity = new set<Id>();
for(Sample_Transaction__c objOpp: trigger.new){
set_Opportunity.add(objOpp.Parent_id__c);
}
Decimal Sum;
Sum=0;
for(Sample_Transaction__c sample_transaction : [SELECT id,Sample_Lot_ID__c, Transaction_Quantity__c FROM Sample_Transaction__c WHERE Parent_id__c = : set_Opportunity
]){
Sum+= sample_transaction.Transaction_Quantity__c;
for(Sample_Lot__c objAccount : [SELECT Id, Quantity_Left__c FROM Sample_Lot__c WHERE Id = : sample_transaction.Sample_Lot_ID__c]){
objAccount.Quantity_left__c = Sum ;
list_Account.add(objAccount);
update objAccount ;
}
}
}
Hi Somasundaram, Since, Your Code logic is same for Insert/Update and Delete, you are facing this problem. Consider using Trigger Context Variables.
if (Trigger.isInsert || Trigger.isUpdate) {
// Your logic for Insert/Update
}
if (Trigger.isDelete) {
// Your logic for Delete
}
if (Trigger.isUndelete) {
// Your logic for Undelete
}
And Also Note the below details about availablity of a record in Trigger List during different events.
I believe, you are getting "Attempt to de-reference a null object " Error because you are trying to access the deleted record from trigger.new in Trigger Delete event. or something like that. In a nut shell, Handle the code differently for different events with suitable trigger.New and trigger.Old lists.Hope it helps...Best,Nithesh.| Events | trigger.Old | trigger.New |
| -------------- |---------------| ------------:|
| After Delete | Yes | No |
| After Undelete | No | Yes |