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
rama krishna 181rama krishna 181 

trigger Compare_OldandNewvalues on Account (before update) { for (Account acc: Trigger.new) { Account oldAccount = Trigger.oldMap.get(acc.ID); if(acc.AccountNumber != oldAccount.AccountNumber) { // can you explain this code

hi ,
trigger Compare_OldandNewvalues on Account (before update) {  
  for (Account acc: Trigger.new) {  
      Account oldAccount = Trigger.oldMap.get(acc.ID);      
  if(acc.AccountNumber != oldAccount.AccountNumber) {
// can you explain this code 
Suraj TripathiSuraj Tripathi
Hi Rama,

I will try to make clear these lines of code line by line.

This Code is for this type of requirement

Suppose,  if we have a account which has ID = '0017685439ScH43'
and it has values Account no ='1234' and Name = 'Rama'

And now we are updating its
Account Number ='4567'


 
trigger Compare_OldandNewvalues on Account (before update) {
/*this line is running trigger on Account before updating any record of Account */
 
for (Account acc: Trigger.new) {
/* this line is iterating with trigger.new which has all "new" values of that account which is currently being updated */
   
Account oldAccount = Trigger.oldMap.get(acc.ID);   
/* this line has oldAccount Variable which has 'old' values of that account which is being updated */
 
if(acc.AccountNumber != oldAccount.AccountNumber) {
/* here we are checking that if the old account number of account is same as new account number, if it is not same as old account number then perform some action inside if condition */




if any doubt , you can ask me, 
I hope it is helpful for you, if it really helps you, then please mark this as best, to remove this question from unsolved threads
Regards
Suraj
rama krishna 181rama krishna 181
tq tq tq
USoni_SFDevUSoni_SFDev
SOLUTION  - With Best Code
trigger MyTrigger on Account(before insert, before update) {
    //For insert only
    Set<String> strSet = new Set<String>(); 
    for(Account acc : Trigger.New){
        strSet.add(acc.Name);
    }
    for(Account acc : [SELECT Name FROM Account Where Name IN : strSet]){
        if(Trigger.isInsert){
            acc.addError('Could not insert the account with the same name');
        }else if(Trigger.isUpdate){
            Account oldAccount = Trigger.oldMap.get(acc.id);
            Account newAccount = Trigger.newMap.get(acc.id);    
            if(oldAccount.Name == newAccount.Name){
                acc.addError('Could not update the account with the same name');
            }else{
                //Do something 
            }
        }
    }
}
Ubaidullah BaigUbaidullah Baig
List<id> AccId= new list<id>();
    for(Account acc : Trigger.new)
    {

        if(acc.id!= Trigger.oldMap.get(acc.id))
        {
            AccId.add(acc.Id);
        }