+ Start a Discussion
Arpita NayakArpita Nayak 

trigger.old example

Hi can any one explain this code .If required please simplify the code also.

trigger emailCheck on Employee__c (before update) 
{
    Map<Id,Employee__c> o = new Map<Id,Employee__c>();
    o = trigger.oldMap;
    for(Employee__c n : trigger.new)
    {
        Employee__c old = new Employee__c();
        old = o.get(n.Id);
        if(n.Email__c != old.Email__c)
        {
            n.Email__c.addError('Email cannot be changed');
        }
    }
}
 
Best Answer chosen by Arpita Nayak
Amit Chaudhary 8Amit Chaudhary 8
Please try to use Trigger.oldMap
trigger emailCheck on Employee__c (before update) 
{
    for(Employee__c n : trigger.new)
    {
        Employee__c old = Trigger.oldMap.get(n.id);
        if(n.Email__c != old.Email__c)
        {
            n.Email__c.addError('Email cannot be changed');
        }
    }
}

Let us know if this will help you
 

All Answers

Mahesh DMahesh D
Hi Arpita,

Please check the below code along with comments.

I also simplified the code:

 
// Trigger on Employee__c for 'before insert'
trigger EmailCheckTrigger on Employee__c (before update) {
    
	// Iterate through the input records.
    for(Employee__c emp: Trigger.new) {
		// Compare the new Email value with old Email value.
		// If both are different then it means, there is a change in the email.
        if(emp.Email__c != Trigger.oldMap.get(emp.Id).Email__c) {
			// Add error message to the Email field.
            emp.Email__c.addError('Email cannot be changed');
        }
    }
}

Please do let me know if it helps you.

Regards,
Mahesh
Automate ProcessAutomate Process
The trigger is simply checking if the Email field has been changed. If the email field has been changed, it will throw an error saying "Email cannot be changed".
So, basically, its a trigger that disables users to edit the email.
Amit Chaudhary 8Amit Chaudhary 8
Please try to use Trigger.oldMap
trigger emailCheck on Employee__c (before update) 
{
    for(Employee__c n : trigger.new)
    {
        Employee__c old = Trigger.oldMap.get(n.id);
        if(n.Email__c != old.Email__c)
        {
            n.Email__c.addError('Email cannot be changed');
        }
    }
}

Let us know if this will help you
 
This was selected as the best answer
Arpita NayakArpita Nayak
Thanx Amit its working properly,but i have one confusion regarding Trigger.oldMap.get(n.id)
 
Amit Chaudhary 8Amit Chaudhary 8
you can Trigger context variable on below post.
1) http://amitsalesforce.blogspot.in/2015/10/trigger-context-variables.html
2) http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

Trigger.oldMap A map of IDs to the old versions of the sObject records.Note that this map is only available in update and delete triggers.