[SalesForce] Trigger checkbox when Insert/Update

I would like to update the checkbox field 'New' to false when there's a new record inserted or updated when the colID is more than the previous colID.

For instance:
My record as shown:

ProdID = 1
ColID = 5
New = True

ProdID = 2
ColID = 6
New = True

So basically after ProdID =2 is inserted, ProdID = 1 record checkbox field should be updated to false

I've tried the below Trigger:

Public Decimal colold;
Public Boolean newiold;

List<Product__c> productsToUpdate = new List<Product__c>{};
List<Product__c> prodList = [SELECT Name,Collection__c, New__c FROM Product__c where Id in : Trigger.new];

Id selid;


for(Product__c pold : Trigger.new){
     if (pold.New__c == true) {    
         selid = pold.id;
    }
 }

for(Product__c aa: prodList)
{
   if(aa.Id == selid && colold > aa.Collection__c)
   {
      aa.New__c=false;
      productsToUpdate.add(aa);
   }
}
update productsToUpdate;

Best Answer

Try following approach :

List<Product__c> productsToUpdate = new List<Product__c>{};
//Insert scenario
public void handleAfterInsert(){
    List<Product__c> prodList = [SELECT Name,Collection__c, New__c FROM Product__c];

    for(Product__c newproduct : Trigger.new){
         for( Product__c oldproduct : prodList)
         {
           if(newproduct.Collection__c > oldproduct.Collection__c)
           {
             newproduct.New__c = true;
             oldproduct.New__c = false;
             productsToUpdate.add(oldproduct);
           }
         }
     }

}

public void handleAfterUpdate(){
//Update scenario
//Exclude the current records and get all the previous ones
    List<Product__c> prodList = [SELECT id, Name,Collection__c, New__c FROM Product__c
                                  Where id not in : Trigger.new];

    for(Product__c newproduct : Trigger.new){
         for( Product__c oldproduct : prodList)
         {
           if(newproduct.Collection__c > oldproduct.Collection__c)
           {
             newproduct.New__c = true;
             oldproduct.New__c = false;
             productsToUpdate.add(oldproduct);
           }
         }
     }

}

update productsToUpdate;
Related Topic