function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bonny mankotiabonny mankotia 

Trigger old and new value

Hello guys.I have this simple trigger i need to compare old and new values for this trigger and if its not match then update the phone field.Can somebody sort out this problem with code?

trigger SameobjTrg on Contact (before insert) 
{
    for(contact con:trigger.new)
    {
        con.MobilePhone = '98765436523';
      }
}
Best Answer chosen by bonny mankotia
Tarun J.Tarun J.
Hello Bonny,

Your trigger is on Before Insert event. Their is old value when you insert any record. Hence it will not work to compare two values. 
If you want to compare old and new value, you can do it in Update call.
trigger SameobjTrg on Contact (before Update) 
{
    for(Interger i=0; i<trigger.new.size(); i++)
    {
             if(trigger.new[i].MobilePhone != trigger.old[i].MobilePhone){

                   trigger.new[i].MobilePhone = '98765436523';
             }
      }
}
-Thanks,
TK
 

All Answers

Tarun J.Tarun J.
Hello Bonny,

Your trigger is on Before Insert event. Their is old value when you insert any record. Hence it will not work to compare two values. 
If you want to compare old and new value, you can do it in Update call.
trigger SameobjTrg on Contact (before Update) 
{
    for(Interger i=0; i<trigger.new.size(); i++)
    {
             if(trigger.new[i].MobilePhone != trigger.old[i].MobilePhone){

                   trigger.new[i].MobilePhone = '98765436523';
             }
      }
}
-Thanks,
TK
 
This was selected as the best answer
Waqar Hussain SFWaqar Hussain SF
trigger SameobjTrg on Contact (before insert) 
{
    for(contact con:trigger.new)
    {
		if(Trigger.oldMap.get(con.Id).MobilePhone == con.MobilePhone)
			con.adderror('mobile number is same');
      }
}
Krishna SambarajuKrishna Sambaraju
You can compare the old value and new valuel in before update trigger, not in before insert trigger.
Here is an example of comparing the old and new valuels in a trigger.
trigger SameobjTrg on Contact (before update) 
{
    for(contact con:trigger.new)
    {
        if(trigger.oldMap.get(con.Id).MobilePhone != con.MobilePhone)
        {
             //dome some thing here
        }
      }
}
For the scenario you mentioned above, you don't need a trigger. If the value is not changed, it won't update any way.
 
Waqar Hussain SFWaqar Hussain SF
Please don't forget to mark "BEST ANSWER" for the most helpful solution.
bonny mankotiabonny mankotia
Thanks Krishna Sambaraju its working for me.
bonny mankotiabonny mankotia
Thanks vickey for Helping.