0

Im trying to create a Trigger on my Products. Would like to update the New checkbox field to false if the col is more than the newly inserted col and if the checkbox field is true. However the trigger codes below does not work.

trigger NewIn on Product__c (after insert, before update) {

Product__c prod = new Product__c(); 
  List<Product__c> productsToUpdate = new List<Product__c>{};

    for(Product__c p : Trigger.new){
        Decimal col = p.Collection__c;
        Boolean newi = p.New__c;

        if(p.Collection__c > col){
            if (newi == true){
                newi = false;
                productsToUpdate.add(p);
            }

        }

    }//end for
    update productsToUpdate;

}
  • Here you are just assigning the collection__c to col and checking the same so it will always be the same. – Maruf Bagwan Mar 26 '15 at 5:37
0

I believe you can achieve this with a workflow rule + field update without a trigger.

Use a rule criteria something like

AND(
  PRIORVALUE(Collection__c) > Collection__c,
  New__c
)

and then use a field update action to set the checkbox value to false.

but if you want to go ahead with the trigger, then you just need to handle before update event and make some tweaks to your code.

in your current code you comparing the values of the same incoming record instead of comparing the old value & the new value.

check this article to understand more on the trigger context variables.

your trigger should be something like this..

trigger NewIn on Product__c (before update) {

    for(Product__c p : Trigger.new){
        Product__c oldP = trigger.oldMap(p.Id);    
        if(oldP.Collection__c > p.Collection__c && p.New__c)
           p.New__c = false;        
    }   

}
  • thank you! I tried both method, but the checkbox field is still not updated. :( – fb69 Mar 26 '15 at 8:01
0

You can try this code.

trigger NewIn on Product__c (after insert, after update) {

Product__c prod = new Product__c(); 
  List<Product__c> productsToUpdate = new List<Product__c>{};
Public   Decimal colnew;
Public Boolean newinew;
Public   Decimal colold;
Public Boolean newiold;

 for(Product__c pold : Trigger.old){
        Decimal colold = pold.Collection__c;
        Boolean newiold = pold.New__c;
       }

 for(Product__c pnew : Trigger.new){
        Decimal colnew = p.Collection__c;
        Boolean newinew = p.New__c;

       if(colnew  > colold){
            if (newinew == true){
               pnew.New__c =false;
                productsToUpdate.add(pnew) ;
            }

        }
       }

    update productsToUpdate;

}
  • thanks for your soln. However, the trigger does not work.The checkbox field is not updated. – fb69 Mar 26 '15 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.