+ Start a Discussion
Ramana VRamana V 

Trigger to get old and new values of number

Hi All,
I have one number field called seats__c in custom object. My requirement is when I change Seats__c value, I want to capture subtraction of old and new value in another number field(Removed__c). I have written trigger as below. But I am getting some error on this. Can anyone tell me that where I am doing wrong. Please see my code below.
 
trigger quanCol on College__c (after update) {
    List<college__c> collist = [select id,Seats__c, Removed__c from College__c where Id =: Trigger.New];
    for(College__c c : collist)
    {
            c.removed__c = c.Seats__c - trigger.oldMap.get(c.id).Seats__c;
        
    }
    update collist;
}
Please help me here. Thanks in Advance
Error
User-added image
Best Answer chosen by Ramana V
Malika Pathak 9Malika Pathak 9

Hi Ramana,

Please Find the solution.

trigger UpdateRemovedField on College__c (before Update) {
    
    if(trigger.isBefore){
        if(trigger.isUpdate){
            Update_ApexClass.method(trigger.old,Trigger.new);
           
        }
    }

}

public class Update_ApexClass {
    public static void method(List<College__c> oldList,List<College__c> newList){
        for(College__c cs:oldList){
            for(College__c cs1:newList){
               cs1.Removed__c=cs.Seats__c-cs1.Seats__c;
 
            }            
        }
        
    }
}

If it will help you Please mark best answer

Thanks

All Answers

AbhishekAbhishek (Salesforce Developers) 
Try the suggestions as mentioned in the below discussions,

https://help.salesforce.com/articleView?id=000313950&type=1&mode=1

https://salesforce.stackexchange.com/questions/84646/apex-cannot-insert-update-activate-entity-self-reference-from-trigger


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks.
Malika Pathak 9Malika Pathak 9

Hi Ramana,

Please Find the solution.

trigger UpdateRemovedField on College__c (before Update) {
    
    if(trigger.isBefore){
        if(trigger.isUpdate){
            Update_ApexClass.method(trigger.old,Trigger.new);
           
        }
    }

}

public class Update_ApexClass {
    public static void method(List<College__c> oldList,List<College__c> newList){
        for(College__c cs:oldList){
            for(College__c cs1:newList){
               cs1.Removed__c=cs.Seats__c-cs1.Seats__c;
 
            }            
        }
        
    }
}

If it will help you Please mark best answer

Thanks

This was selected as the best answer