Thursday 13 March 2014

Trigger to Revert field to Old value.

Once working on a requirement i had a use-case like this :-
The user creates a product for example Pen with a cost of 500 and saves it, Now the user wants to update this price.
He can either increase the price or increase it.
If the user increases the price then it should be saved.
So my work to do was : - If the user gives a new price less than  first price then the record should be saved without any error messages and old price should reflect back to price field.

Let me explain in a diagrammatic way : - 
Price Increasing                                                             Price Decreasing
Initial price : - 500                                                       Initial price : - 500                    

New Price : - 600                                                      New Price:- 300

Price after saving :- 600.                                            Price after saving :- 500

Here is the Trigger Code :
 trigger trigbeforeupdate on member__c (before update) {  
    List<Member__c> toUpdate=new List<Member__c>();  
   for (Member__c member : trigger.new)  
   {  
     String newVal=member.Price__c;  
     String oldVal=trigger.oldMap.get(member.id).Price__c;  
      if (newVal < oldVal)  
     {  
       member.Text__c= oldVal;  
     }  
     else{  
      member.Text__c= newVal;  
      }  
   }  
 }  
-