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
Anna SuganthiAnna Suganthi 

Hi all, I need some help in creating a trigger for the following requirement,

Create a new trigger to automatize the fulfillment of this field with other existing activity(ID) if the following conditions are true:
A new activity(event) is created with:
Type = meeting
Created by a user with Profile Name starting with "Sales Representative".
Subject contains "Initial Meeting" and does not contain "Additional" nor "Cancelled" nor "Resch".
The existing Activity (event) meets the following :
Subject does not contain "Additional" nor "Cancelled" nor "Resch".
Subject contains "Initial Meeting".
The contact/lead (WhoId) has the same Name in both activities (events).
The Start Date of both activities (events) is the same or separated 3 days at most.
If more than one match is found, select the oldest activity(event).

I tried the following, but am stuck in getting the user name with profile "Sales Representative"
trigger eventSetSameAs on Event (before insert) {
    Map<ID, Event> sameEvent = new Map<ID, Event>();
    //Check for the new event
    for(Event newEvent: system.trigger.new){
        Event oldEvent = System.Trigger.oldMap.get(newEvent.Id);
        //Get the list of users with profile Sales Representative
        List<User> userProfiles = [SELECT Id, Profile.Name FROM User WHERE Id IN : trigger.newMap.keySet() and Profile.Name = 'Sales Representative'];
        //Check for the following conditions
        if(newEvent.Type == 'Meeting' && 
           ((trigger.newMap.get(newEvent.id).subject.contains('Initial Meeting')) && 
             (!trigger.newMap.get(newEvent.id).subject.contains('Additional')) || 
              (!trigger.newMap.get(newEvent.id).subject.contains('Canceled')) || 
               (!trigger.newMap.get(newEvent.id).subject.contains('Resch')))) {
           if(newEvent.CreatedBy == )
            newEvent.Same_As__c = oldEvent.Id;
            }
        }
    }
Can you please help me in completing this trigger?
TIA
Waqar Hussain SFWaqar Hussain SF
try below apex code, it is a mockup, not tested.
trigger eventSetSameAs on Event (before insert) {
	Map<Id, User> UsersMap = new Map<Id, User>([SELECT Id, Name, Profile.Name FROM user WHERE isActive = true]);

    //Check for the new event
    for(Event newEvent: trigger.new){
        if(newEvent.Type == 'Meeting' && UsersMap.get(newEvent.CreatedById).Profile.Name.StartsWith('Sales Representative') && newEvent.subject.contains('Initial Meeting') && (!newEvent.subject.contains('Additional') || !newEvent.subject.contains('Canceled') || !newEvent.subject.contains('Resch'))){
           list<Event> ExistingEvents = new list<Event>();
		   ExistingEvents = [Select Id, Subject From Event Where Subject like '%Initial Meeting%' AND ((NOT Subject like '%Additional%') OR (NOT Subject like '%Cancelled%') OR (NOT Subject like '%Resch%')) AND WhoId = newEvent.WhoId AND ActivityDate = newEvent.ActivityDate Order by CreatedDate desc limit 1];
		   
		   //Do whatever you want with exisitng activities.
        }
    }
}


 
Anna SuganthiAnna Suganthi

Hi, 
Thanks for your reply, but the psuedo code is this way, so i modified the trigger,

"- MAP eventstoInsert<ID, whoid> - MAP eventsSameAs<WhoId, relatedId> - If the user who is inserting the Event has a [Profile Name starting with ""Sales Representative""]* THEN - Go through the trigger.new - If (Type = Meeting AND Subject contains ""Initial Meeting"" and subject does not contain ""Additional"" nor ""Cancelled"" nor ""Resch"") THEN - Put the Event into the MAP eventstoInsert<ID, WHOID**> -END IF - Get a MAP eventsSameAs<Id, relatedId> with Ids of old Events in DB. For this we must query th DB in order to get the events... 1. Related to the same lead/contact than the Event is being inserted (whose WhoId is IN the WhoIds in our MAP eventstoInsert). 2. Subject contains ""Initial Meeting"" 3. Subject does not contain ""Additional"" nor ""Cancelled"" nor ""Resch"" and StartDate is 3 days previous at most 4. If there are more than one old Event with the same WhoID (several eventId to put in the SameAs field), we have to choose the oldest. For this, we must do a GROUP BY WhoID and get the one with the oldest CreatedDate. - Put it into the MAP eventsSameAs<WhoID, relatedID> - Go through the MAP eventstoInsert in order to set the SameAs field (if applicable) - Check if eventstoInsert.WhoID is in MAP eventsSameAs.keySet() - trigger.newMap.get(eventstoInsert.Id).SameAs = the corresponding relatedId in the MAP eventsSameAs. * 1- Get the Profile ID of the current user who is inserting the Event [Id profileId = UserInfo.getProfileId()]. 2- Get the profile Name quering the DB 3- Check if the profile Name starts with ""Sales Representative"" Id profileId = UserInfo.getProfileId(); String profileName=[Select Id,Name from Profile where Id=:profileId].Name; ** The WhoId will be used later to look for the other old Events in the DB that match with the Event we are inserting "

The trigger that i have written is, 

trigger eventSetSameAs on Event (before insert) {

Map<ID, String> eventstoInsert= new Map<ID,String>();
Map<String, String> eventSameAs= new Map<String,String>();

Id profileId = UserInfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;  

(if profileName.StartsWith('Sales Representative') ){

for(Event newEvent: system.trigger.new) {

     if(newEvent.Type == 'Meeting' && newEvent.subject.contains('Initial Meeting') && (!newEvent.subject.contains('Additional') && !newEvent.subject.contains('Canceled') && !newEvent.subject.contains('Resch'))){
         eventstoInsert.put(event.WhoId, new Map<ID, String>());
         }
         
         List<Event> ExistingEvents = ([select WhoID, StartDateTime  from Event where WhoId IN :eventstoInsert.keySet() and Subject like '%Initial Meeting%' AND 
                            ((NOT Subject like '%Additional%') AND (NOT Subject like '%Cancelled%') AND (NOT Subject like '%Resch%')) and StartDateTime >= :Date.Today().addDays(-3) AND StartDateTime <= TODAY" GROUP BY WhoID ORDER BY CreatedDate desc]);
         
       if( ExistingEvents.WhoId > 1) {
       
       eventSameAs.put(ExistingEvents.CreatedId, new Map<String, String>());
       }
         
Any help would be appreciated. Thanks,

Waqar Hussain SFWaqar Hussain SF
So what issue are you facing now? is that trigger not working?
Anna SuganthiAnna Suganthi
I need to get the oldest ID of a WhoID and put them in a map. 

List<Event> ExistingEvents = ([select Id, WhoID from Event where WhoId IN :eventsToUpdate and Subject like '%Initial Meeting%' AND 
                                       ((NOT Subject like '%Additional%') AND (NOT Subject like '%Cancelled%') AND (NOT Subject like '%Resch%')) and (StartDateTime >= LAST_N_DAYS:3 AND StartDateTime <= NEXT_N_DAYS:3) ORDER BY WhoId asc, createdDate asc]); 
        
        for(Event oldEvents: ExistingEvents ){
            eventsSameAs.put(oldEvents.WhoId, oldEvents.Id);

In this part am ordering by based on the Created date. So I should get the ID of the oldest Date to put in to the Map. How to do that?
Waqar Hussain SFWaqar Hussain SF
List<Event> ExistingEvents = ([select Id, WhoID from Event where WhoId IN :eventsToUpdate and Subject like '%Initial Meeting%' AND 
                                       ((NOT Subject like '%Additional%') AND (NOT Subject like '%Cancelled%') AND (NOT Subject like '%Resch%')) and (StartDateTime >= LAST_N_DAYS:3 AND StartDateTime <= NEXT_N_DAYS:3) ORDER BY createdDate asc]); 
        
        for(Event oldEvents: ExistingEvents ){
            eventsSameAs.put(oldEvents.WhoId, oldEvents.Id);

try this
Anna SuganthiAnna Suganthi
"Go through the LIST with the results of the query and put into the MAP eventsSameAs<WhoID, ID> --the first ID for each WhoId"

It is the pseudocode for that line. When I add the ID and WhoID to the Map, i should get only the first ID for each who ID from that list. Not to change the SOQL.
Waqar Hussain SFWaqar Hussain SF
Then you can simply use ContainsKey method, that will check if the whoID is already added to the map, that will not override the value. 
 
for(Event oldEvents: ExistingEvents ){
    !if(eventsSameAs.containsKey(oldEvents.WhoId)
	eventsSameAs.put(oldEvents.WhoId, oldEvents.Id);
}

 
Anna SuganthiAnna Suganthi
Sure, will try, thanks!