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
MS123456MS123456 

how to Write Handler class On this Trigger can you Explain me also write Test class on this trigger

Hi Team pls Help me its Very Urgent..................
trigger eventTriggerContact on Event (after insert, after update) {

   Set<Id> set_ContactId = new Set<Id>();
   List<Contact> conList = new List<Contact>(); 
     
    
    
   if(Trigger.isAfter && Trigger.isInsert)
     {
       for(Event e : Trigger.new)
         {
           
           if(e.whoId!=null && String.valueOf(e.whoId).startsWith('003') && (e.Type == 'Consult') )
             {
               set_ContactId.add(e.whoId);
             }
        }
        
    
    Map<Id,Contact> conMap = new Map<Id,Contact>([Select Id,StartDateTime__c,Start_Time__c,User_Attorney_Profile_Page__c,User_First_Name__c,
                                               User_Last_Name__c,User_Office_Google_Map_Link__c,User_Office_Phone__c,Phone_Number_Text__c,
                                               User_Office_Website__c,One_of_Our_Attorneys__c,Most_Recent_Event_Id__c from contact where Id IN:set_ContactId]);  
                                               
  
    
                                                 
         
        for(Event e : Trigger.new)
          {
           
            if(conMap!=null && conMap.containsKey(e.whoId))
              
              {
                   conMap.get(e.whoId).StartDateTime__c= e.StartDateTime;
                   conMap.get(e.whoId).Start_Time__c= e.Start_Time__c;
                   conMap.get(e.whoId).User_Attorney_Profile_Page__c= e.User_Attorney_Profile_Page__c;
                   conMap.get(e.whoId).User_First_Name__c= e.User_First_Name__c;
                   conMap.get(e.whoId).User_Last_Name__c= e.User_Last_Name__c;
                   conMap.get(e.whoId).User_Office_Google_Map_Link__c= e.User_Google_Map_Link__c;
                   conMap.get(e.whoId).User_Office_Phone__c= e.User_Office_Phone__c;
                   conMap.get(e.whoId).User_Office_Website__c = e.User_Office_Website__c ;
                   conMap.get(e.whoId).Phone_Number_Text__c= e.Phone_Number_Text__c;
                   conMap.get(e.whoId).Great_Hands_Text__c= e.Great_Hands_Text__c;
                   conMap.get(e.whoId).One_of_Our_Attorneys__c= e.One_of_Our_Attorneys__c;
                   conMap.get(e.whoId).Most_Recent_Event_Id__c=e.id;
                   conList.add(conMap.values());
              }
          }
        
          
         system.debug('!!!!!!'+ conList);
          if(conList!=null && conList.size()>0)
             update conList;
   
  }        
      if(Trigger.isAfter && Trigger.isUpdate)
      {                                                  
    for(Event e : Trigger.new)
         {
           
           if(e.whoId!=null && String.valueOf(e.whoId).startsWith('003') && (e.Type == 'Consult'))
             {
               set_ContactId.add(e.whoId);
             }
        }
        
    
    Map<Id,Contact> conMap = new Map<Id,Contact>([Select Id,StartDateTime__c,Start_Time__c,User_Attorney_Profile_Page__c,User_First_Name__c,
                                               User_Last_Name__c,User_Office_Google_Map_Link__c,User_Office_Phone__c,Phone_Number_Text__c,
                                               User_Office_Website__c,One_of_Our_Attorneys__c,Most_Recent_Event_Id__c from contact where Id IN:set_ContactId]);  
                                               
  
    
                                                 
         
        for(Event e : Trigger.new)
          {
           
            if(conMap!=null && conMap.containsKey(e.whoId) && e.id  == conMap.get(e.whoId).Most_Recent_Event_Id__c)
              
              {
                   conMap.get(e.whoId).StartDateTime__c= e.StartDateTime;
                   conMap.get(e.whoId).Start_Time__c= e.Start_Time__c;
                   conMap.get(e.whoId).User_Attorney_Profile_Page__c= e.User_Attorney_Profile_Page__c;
                   conMap.get(e.whoId).User_First_Name__c= e.User_First_Name__c;
                   conMap.get(e.whoId).User_Last_Name__c= e.User_Last_Name__c;
                   conMap.get(e.whoId).User_Office_Google_Map_Link__c= e.User_Google_Map_Link__c;
                   conMap.get(e.whoId).User_Office_Phone__c= e.User_Office_Phone__c;
                   conMap.get(e.whoId).User_Office_Website__c = e.User_Office_Website__c ;
                   conMap.get(e.whoId).Phone_Number_Text__c= e.Phone_Number_Text__c;
                   conMap.get(e.whoId).Great_Hands_Text__c= e.Great_Hands_Text__c;
                   conMap.get(e.whoId).One_of_Our_Attorneys__c= e.One_of_Our_Attorneys__c;
                   
                   conList.add(conMap.values());
              }
          }
        
          
         system.debug('!!!!!!'+ conList);
          if(conList!=null && conList.size()>0)
             update conList;
   
  }        
}

Pls Help Me its Very Very Urgent..........
Best Answer chosen by MS123456
Nayana KNayana K
Handler class: 
public class EventHandler
{
	public void onAfterInsert(List<Event> lstNewEvent)
	{
		populateMostRecentOnContact(lstNewEvent, new Map<Id, Event>());
	}
	
	public void onAfterUpdate(List<Event> lstNewEvent, Map<Id, Event> mapOldEvent)
	{
		populateMostRecentOnContact(lstNewEvent, mapOldEvent);
	}
	
	private void populateMostRecentOnContact(List<Event> lstNewEvent, Map<Id, Event> mapOldEvent)
	{
		Map<Id,Contact> conMap = new Map<Id,Contact>();
		Contact objCon;
	
		for(Event e : lstNewEvent)
		{
			/** What if in future salesforce changes prefix from 003 to 999 after some days?!! Old code doesn't work. Let's make it dynamic */
			/* 	1. On Insert
					OR
				2. On Update, only if specific field - values are changes 
			*/
			if(Trigger.isAfter && e.whoId != null && e.whoId.getSObjectType() == Contact.SobjectType && e.Type == 'Consult'
				&& 
				(	Trigger.isInsert 
					||
					(Trigger.isUpdate && 
						(
							e.StartDateTime__c != mapOldEvent.get(e.Id).StartDateTime__c
							||
							e.Start_Time__c != mapOldEvent.get(e.Id).Start_Time__c
							||
							e.User_Attorney_Profile_Page__c != mapOldEvent.get(e.Id).User_Attorney_Profile_Page__c
							||
							e.User_First_Name__c != mapOldEvent.get(e.Id).User_First_Name__c
							||
							e.User_Google_Map_Link__c != mapOldEvent.get(e.Id).User_Google_Map_Link__c
							||
							e.User_Office_Website__c != mapOldEvent.get(e.Id).User_Office_Website__c
							||
							e.User_Office_Phone__c != mapOldEvent.get(e.Id).User_Office_Phone__c
							||
							e.Phone_Number_Text__c != mapOldEvent.get(e.Id).Phone_Number_Text__c
							||
							e.Great_Hands_Text__c != mapOldEvent.get(e.Id).Great_Hands_Text__c
							||
							e.One_of_Our_Attorneys__c != mapOldEvent.get(e.Id).One_of_Our_Attorneys__c
						)
					)
				)
					
			  )
			{	
				objCon = new Contact(Id = e.whoId);
				objCon.StartDateTime__c = e.StartDateTime__c;
				objCon.Start_Time__c = e.Start_Time__c;
				objCon.User_Attorney_Profile_Page__c = e.User_Attorney_Profile_Page__c;
				objCon.User_First_Name__c = e.User_First_Name__c;
				objCon.User_Last_Name__c = e.User_Last_Name__c;
				objCon.User_Office_Google_Map_Link__c = e.User_Google_Map_Link__c;
				objCon.User_Office_Phone__c = e.User_Office_Phone__c;
				objCon.User_Office_Website__c = e.User_Office_Website__c ;
				objCon.Phone_Number_Text__c = e.Phone_Number_Text__c;
				objCon.Great_Hands_Text__c = e.Great_Hands_Text__c;
				objCon.One_of_Our_Attorneys__c = e.One_of_Our_Attorneys__c;
				objCon.Most_Recent_Event_Id__c = e.id;
				conMap.put(e.whoId, objCon);
			}
		}

		system.debug('!!!!!!'+ conMap);
		if(!conMap.isEmpty())
			update conMap.values();
		}
	}
}
 

Trigger:
trigger eventTriggerContact on Event (after insert, after update) 
{
	EventHandler objHandler = new EventHandler();
	
	if(Trigger.isAfter)
	{
		if(Trigger.isInsert)
		{
			objHandler.onAfterInsert(Trigger.New);
		}
		else if(Trigger.isUpdate)
		{
			objHandler.onAfterUpdate(Trigger.New, Trigger.oldMap);
		}
	}
}

Follow the instructions for the test class and complete by yourself:
@isTest 
private class eventTriggerContactTest 
{
    static testMethod void testMostRecentUpdation() 
	{
		/* Prepare Test Data - START */
		Contact objContact = new Contact(LastName = 'TestCon' /* Fill other necessary field-value pairs here*/);
		insert objContact;
		/* Prepare Test Data - END */
		
		// insert event
		Event objEvent = new Event();
		objEvent.Type = 'Consult';
		objEvent.Description = 'Test Desc'; 
		objEvent.WhatId = objContact.Id; 
		/* Here you have to populate a field which you can update later. Say objEvent.ABC__c = 'DUMMY';*/
		insert objEvent;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
		
		// insert one more event
		Event objEvent2 = new Event();
		objEvent2.Type = 'Consult';
		objEvent2.Description = 'Test Desc'; 
		objEvent2.WhatId = objContact.Id; 
		insert objEvent2;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent2.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
		
		/* Update specific field on the first event (The one which are not formula but used inside the formula which causes the control to go inside update logic).
			Say, objEvent.ABC__c = 'CHANGED';*/
		update objEvent;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
}

Please let me know if you face any issues.
 

All Answers

Nayana KNayana K
Handler class: 
public class EventHandler
{
	public void onAfterInsert(List<Event> lstNewEvent)
	{
		populateMostRecentOnContact(lstNewEvent, new Map<Id, Event>());
	}
	
	public void onAfterUpdate(List<Event> lstNewEvent, Map<Id, Event> mapOldEvent)
	{
		populateMostRecentOnContact(lstNewEvent, mapOldEvent);
	}
	
	private void populateMostRecentOnContact(List<Event> lstNewEvent, Map<Id, Event> mapOldEvent)
	{
		Map<Id,Contact> conMap = new Map<Id,Contact>();
		Contact objCon;
	
		for(Event e : lstNewEvent)
		{
			/** What if in future salesforce changes prefix from 003 to 999 after some days?!! Old code doesn't work. Let's make it dynamic */
			/* 	1. On Insert
					OR
				2. On Update, only if specific field - values are changes 
			*/
			if(Trigger.isAfter && e.whoId != null && e.whoId.getSObjectType() == Contact.SobjectType && e.Type == 'Consult'
				&& 
				(	Trigger.isInsert 
					||
					(Trigger.isUpdate && 
						(
							e.StartDateTime__c != mapOldEvent.get(e.Id).StartDateTime__c
							||
							e.Start_Time__c != mapOldEvent.get(e.Id).Start_Time__c
							||
							e.User_Attorney_Profile_Page__c != mapOldEvent.get(e.Id).User_Attorney_Profile_Page__c
							||
							e.User_First_Name__c != mapOldEvent.get(e.Id).User_First_Name__c
							||
							e.User_Google_Map_Link__c != mapOldEvent.get(e.Id).User_Google_Map_Link__c
							||
							e.User_Office_Website__c != mapOldEvent.get(e.Id).User_Office_Website__c
							||
							e.User_Office_Phone__c != mapOldEvent.get(e.Id).User_Office_Phone__c
							||
							e.Phone_Number_Text__c != mapOldEvent.get(e.Id).Phone_Number_Text__c
							||
							e.Great_Hands_Text__c != mapOldEvent.get(e.Id).Great_Hands_Text__c
							||
							e.One_of_Our_Attorneys__c != mapOldEvent.get(e.Id).One_of_Our_Attorneys__c
						)
					)
				)
					
			  )
			{	
				objCon = new Contact(Id = e.whoId);
				objCon.StartDateTime__c = e.StartDateTime__c;
				objCon.Start_Time__c = e.Start_Time__c;
				objCon.User_Attorney_Profile_Page__c = e.User_Attorney_Profile_Page__c;
				objCon.User_First_Name__c = e.User_First_Name__c;
				objCon.User_Last_Name__c = e.User_Last_Name__c;
				objCon.User_Office_Google_Map_Link__c = e.User_Google_Map_Link__c;
				objCon.User_Office_Phone__c = e.User_Office_Phone__c;
				objCon.User_Office_Website__c = e.User_Office_Website__c ;
				objCon.Phone_Number_Text__c = e.Phone_Number_Text__c;
				objCon.Great_Hands_Text__c = e.Great_Hands_Text__c;
				objCon.One_of_Our_Attorneys__c = e.One_of_Our_Attorneys__c;
				objCon.Most_Recent_Event_Id__c = e.id;
				conMap.put(e.whoId, objCon);
			}
		}

		system.debug('!!!!!!'+ conMap);
		if(!conMap.isEmpty())
			update conMap.values();
		}
	}
}
 

Trigger:
trigger eventTriggerContact on Event (after insert, after update) 
{
	EventHandler objHandler = new EventHandler();
	
	if(Trigger.isAfter)
	{
		if(Trigger.isInsert)
		{
			objHandler.onAfterInsert(Trigger.New);
		}
		else if(Trigger.isUpdate)
		{
			objHandler.onAfterUpdate(Trigger.New, Trigger.oldMap);
		}
	}
}

Follow the instructions for the test class and complete by yourself:
@isTest 
private class eventTriggerContactTest 
{
    static testMethod void testMostRecentUpdation() 
	{
		/* Prepare Test Data - START */
		Contact objContact = new Contact(LastName = 'TestCon' /* Fill other necessary field-value pairs here*/);
		insert objContact;
		/* Prepare Test Data - END */
		
		// insert event
		Event objEvent = new Event();
		objEvent.Type = 'Consult';
		objEvent.Description = 'Test Desc'; 
		objEvent.WhatId = objContact.Id; 
		/* Here you have to populate a field which you can update later. Say objEvent.ABC__c = 'DUMMY';*/
		insert objEvent;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
		
		// insert one more event
		Event objEvent2 = new Event();
		objEvent2.Type = 'Consult';
		objEvent2.Description = 'Test Desc'; 
		objEvent2.WhatId = objContact.Id; 
		insert objEvent2;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent2.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
		
		/* Update specific field on the first event (The one which are not formula but used inside the formula which causes the control to go inside update logic).
			Say, objEvent.ABC__c = 'CHANGED';*/
		update objEvent;
		// Test that the trigger correctly updated the Most_Recent_Event_Id__c
		System.assertEquals(objEvent.Id, [SELECT Most_Recent_Event_Id__c FROM Contact WHERE Id =: objContact.Id].Most_Recent_Event_Id__c);
}

Please let me know if you face any issues.
 
This was selected as the best answer
MS123456MS123456
Thnx for reply but can u use my code n write handler cls pls pls........
Amit Chaudhary 8Amit Chaudhary 8
Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework
http://amitsalesforce.blogspot.com/2015/06/trigger-best-practices-sample-trigger.html


Your Trigger should be like below
trigger eventTriggerContact on Event (after insert, after update) {

	EventTriggerHandler handler = new EventTriggerHandler();

	If(Trigger.isAfter)
	{
		if(Trigger.isInsert)
		{
			handler.OnAfterInsert(trigger.New);
		}
		else if (Trigger.isUpdate)
		{
			handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
		}
	}

}
Handler class like below
 
public with sharing class EventTriggerHandler 
{
    public void OnAfterInsert( List<Event> newEvent)
    {
        updateContactOnInsert(newEvent);
    }

    public void OnAfterUpdate( List<Event> newEvent, List<Event> oldEvent, Map<ID, Event> newEventMap , Map<ID, Event> oldEventMap )
    {
        updateContactOnUpdate(newEvent,oldEventMap);
    }

	public void updateContactOnUpdate( List<Event> newEvent , Map<ID, Event> oldEventMap )
    {
		for(Event e : newEvent)
        {
			if(e.whoId!=null && String.valueOf(e.whoId).startsWith('003') && (e.Type == 'Consult'))
            {
               set_ContactId.add(e.whoId);
            }
        }
    
		Map<Id,Contact> conMap = new Map<Id,Contact>([Select Id,StartDateTime__c,Start_Time__c,User_Attorney_Profile_Page__c,User_First_Name__c,
                                               User_Last_Name__c,User_Office_Google_Map_Link__c,User_Office_Phone__c,Phone_Number_Text__c,
                                               User_Office_Website__c,One_of_Our_Attorneys__c,Most_Recent_Event_Id__c from contact where Id IN:set_ContactId]);  
         
		for(Event e : newEvent)
		{
			if(conMap!=null && conMap.containsKey(e.whoId) && e.id  == conMap.get(e.whoId).Most_Recent_Event_Id__c)
			{
			   conMap.get(e.whoId).StartDateTime__c= e.StartDateTime;
			   conMap.get(e.whoId).Start_Time__c= e.Start_Time__c;
			   conMap.get(e.whoId).User_Attorney_Profile_Page__c= e.User_Attorney_Profile_Page__c;
			   conMap.get(e.whoId).User_First_Name__c= e.User_First_Name__c;
			   conMap.get(e.whoId).User_Last_Name__c= e.User_Last_Name__c;
			   conMap.get(e.whoId).User_Office_Google_Map_Link__c= e.User_Google_Map_Link__c;
			   conMap.get(e.whoId).User_Office_Phone__c= e.User_Office_Phone__c;
			   conMap.get(e.whoId).User_Office_Website__c = e.User_Office_Website__c ;
			   conMap.get(e.whoId).Phone_Number_Text__c= e.Phone_Number_Text__c;
			   conMap.get(e.whoId).Great_Hands_Text__c= e.Great_Hands_Text__c;
			   conMap.get(e.whoId).One_of_Our_Attorneys__c= e.One_of_Our_Attorneys__c;
			   
			   conList.add(conMap.values());
			}
		}
		
        system.debug('!!!!!!'+ conList);
        if(conList!=null && conList.size()>0)
		{
            update conList;
		}
	}
	
	public void updateContactOnInsert( List<Event> newEvent)
    {
	
		Set<Id> set_ContactId = new Set<Id>();
		List<Contact> conList = new List<Contact>(); 
		for(Event e : newEvent )
		{
			if(e.whoId!=null && String.valueOf(e.whoId).startsWith('003') && (e.Type == 'Consult') )
			{
				set_ContactId.add(e.whoId);
			}
		}
		Map<Id,Contact> conMap = new Map<Id,Contact>([Select Id,StartDateTime__c,Start_Time__c,User_Attorney_Profile_Page__c,User_First_Name__c,
                                               User_Last_Name__c,User_Office_Google_Map_Link__c,User_Office_Phone__c,Phone_Number_Text__c,
                                               User_Office_Website__c,One_of_Our_Attorneys__c,Most_Recent_Event_Id__c from contact where Id IN:set_ContactId]);  

        for(Event e : newEvent )
		{
           
            if(conMap!=null && conMap.containsKey(e.whoId))
            {
                   conMap.get(e.whoId).StartDateTime__c= e.StartDateTime;
                   conMap.get(e.whoId).Start_Time__c= e.Start_Time__c;
                   conMap.get(e.whoId).User_Attorney_Profile_Page__c= e.User_Attorney_Profile_Page__c;
                   conMap.get(e.whoId).User_First_Name__c= e.User_First_Name__c;
                   conMap.get(e.whoId).User_Last_Name__c= e.User_Last_Name__c;
                   conMap.get(e.whoId).User_Office_Google_Map_Link__c= e.User_Google_Map_Link__c;
                   conMap.get(e.whoId).User_Office_Phone__c= e.User_Office_Phone__c;
                   conMap.get(e.whoId).User_Office_Website__c = e.User_Office_Website__c ;
                   conMap.get(e.whoId).Phone_Number_Text__c= e.Phone_Number_Text__c;
                   conMap.get(e.whoId).Great_Hands_Text__c= e.Great_Hands_Text__c;
                   conMap.get(e.whoId).One_of_Our_Attorneys__c= e.One_of_Our_Attorneys__c;
                   conMap.get(e.whoId).Most_Recent_Event_Id__c=e.id;
                   conList.add(conMap.values());
            }
        }
		
        if(conList!=null && conList.size()>0)
		{
             update conList;
		}	
	}
}

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org. 

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Let us know if this will help you