I have created a Event Staging object and a trigger which creates Events/Event Relations after insert of an Event Staging record.

There is a field meetingUID on EventStaging.It is not set set to unique in SF.However if a duplicate field with same meetingUID value is inserted into object, it should fetch and update the original Event Staging object record.

How to achieve this? I am trying in before insert trigger the below code. However a new record gets created every time which leads to record duplication.

Any help appreciated.

   Public class EventnEventRelation 
    Set<string> userset=new set<string>();
    Set<string> EventcreatedBy=new set<string>();
    Set<string> EventMeetingUID=new set<string>();
    List<user> userlist=new List<user>();
    map<string,id> map1=new map<string,id>();
    map<string,string> map2=new map<string,string>();
    map<string,Sobject> map3=new map<string,Sobject>();
    List<Event_Staging__c> userlist1 =new List<Event_Staging__c>();
    List<event> eventlist=new list<event>();
    List<eventrelation> eventrelationlist=new list<eventrelation>();
    List<eventrelation> maineventrelationlist=new list<eventrelation>();
    List<Event_Staging__c > oldeventrelationlist=new list<Event_Staging__c >();
    List<Event_Staging__c > Evstagelist = new List<Event_Staging__c >();
    Set< String > MeetingUidSet = new Set< String >();
    public sObject sobj{get;set;}

    Public EventnEventRelation()
    //Set<string> userset=new set<string>();
    //fetch list of all active Users
    userlist=[Select id,Name,Email from User where IsActive = true];
    //Create a map of emailId and ID of users
    //map<string,id> map1=new map<string,id>();
    for(user us:userlist)

    userlist1=[Select Event_Created_By__c,Meeting_UID__c,Event_Attendees__c,Event_CC__c FROM Event_Staging__c];
    //Create map of meetingUID and eventattendeed of eventstaging
    //map<string,string> map2=new map<string,string>();
    for( Event_Staging__c  Evs1:userlist1)

    for(User Uu:userlist)


    Public void EventmethodBefore(List<Event_Staging__c> ESList)

        for( Event_Staging__c ec : ESList ) MeetingUidSet.add(ec.Meeting_UID__c);
        for( Event_Staging__c  Evss:[Select Id,Meeting_UID__c FROM Event_Staging__c WHERE Meeting_UID__c=:MeetingUidSet])

        for( Event_Staging__c ec : ESList )
            sobj = map3.get(ec.Meeting_UID__c);
            If(sobj !=NULL)
                sobj.put('Name', ec.Name);
                sobj.put('Event_Attendees__c', ec.Event_Attendees__c);
                sobj.put('Event_Attendees__c', ec.Event_Attendees__c);
                sobj.put('Event_CC__c', ec.Event_CC__c);
                sobj.put('Event_Start_Date__c', ec.Event_Start_Date__c);
                sobj.put('Event_End_Date__c', ec.Event_End_Date__c);
                sobj.put('Event_Duration_in_Minutes__c', ec.Event_Duration_in_Minutes__c);
                sobj.put('Event_Location__c', ec.Event_Location__c);
                sobj.put('Meeting_UID__c', ec.Meeting_UID__c);
                sobj.put('Event_Description__c', ec.Event_Description__c);


      Public void Eventmethod(List<Event_Staging__c> ESList)
    //Public void Eventmethod(List<Event_Staging__c> ESList)
    For(Event_Staging__c ES: ESList)

            If(userset.contains(ES.Event_Created_By__c) )
                Event ev = new Event();
                Id Id1=map1.get(ES.Event_Created_By__c);
                system.debug('Event created By'+id1);

                Event ev1 = new Event();



        if(eventlist.size()>0 && eventlist!=NULL)
            system.debug('Eventlist Size------'+eventlist.size());
            insert eventlist;
            system.debug('Eventlist Size------'+eventlist[0]);
            system.debug('Eventlist Size------'+eventlist[0].subject);
        set<string> set3=new set<string>();
        List<Event_Staging__c> UpdateEventstaging = new list<Event_Staging__c>();
        for(Event ECB : eventlist)

        for(Event_Staging__c  EVSCB :[select id,name,Meeting_UID__c FROM Event_Staging__c] )
        If(UpdateEventstaging.size()>0 && UpdateEventstaging!=NULL)
            update UpdateEventstaging;

        for(event ev:eventlist)
                //List<String> ReciepientMail= EVS.Event_Attendees__c.split(',');
                string str=map2.get(ev.Description);
                system.debug('Map1 size---------'+map1.size());
                system.debug('Map2 size---------'+map2.size());
                system.debug('string --------'+str);

                List<String> ReciepientMail= str.split(';');
                for(integer i=0;i<ReciepientMail.size();i++)
                    eventrelation evr=new eventrelation();


       if(maineventrelationlist.size()>0 && maineventrelationlist!=NULL)
             insert maineventrelationlist;
        //delete [select id from Event_Staging__c where id in :Trigger.new];


    Public void DeleteOldEventStagings()
        List<Event_Staging__c > DelList=new List<Event_Staging__c>();
        DelList=[Select Id,name from Event_Staging__c where IsEventCreated__c=FALSE AND CreatedDate <= LAST_N_DAYS:01 ];
        Delete DelList;

  • 2
    Is the meetingUID field set as a unique field? Which original record are you referring to? The original staging record, or the original Event/Relation record? What is MeetingUidSet and map3? Can you please Edit the question with these details.
    – Nick C
    Sep 13, 2016 at 12:36
  • @NickCook MeetingUID is field on Event Staging object. this should be unique. If a record id found with Same MeetingUID, it should be updated with the new details rather than dupliicating.
    – Laxman
    Sep 13, 2016 at 12:53
  • When you say it 'should be unique', is it set as a unique field in salesforce? 'Should' is not very helpful when trying to debug an issue. We need absolutes. Please Edit your question with these answers rather than adding a comment.
    – Nick C
    Sep 13, 2016 at 12:56
  • Hello Tim, it is not set to unique in Salesforce while object creation. However the field is primary key which should be updated rather than duplicated. i have listed the complate class above.
    – Laxman
    Sep 13, 2016 at 13:00
  • 2
    Also, please remove the commented code that's apparently not relevant to your question. I've formatted it so it all is visible. In the future, when pasting code, select it all, then click on the preformatted text icon {} to move it over by 4 spaces.
    – crmprogdev
    Sep 13, 2016 at 13:00

1 Answer 1


You need to run a query for all of the external Id's to see if any of them already exist in your org at the beginning of your trigger. If they do, you need to remove those from your before insert trigger and do an upsert on them instead.


To properly solve your issue, ideally, Meeting_UID__c on the Event_Staging__c object should be set as an ExternalId, especially if you're importing data that references it. From your description, it sounds like that's the case. Any data that's imported should use an Upsert operation, which will then update existing records that contain matching Meeting_UID__c. It then won't be necessary to modify your trigger.

If for some reason you cannot do that, you'll

  1. Want to create a record which has several text fields containing IMA Duplicate and a single new Meeting_UID__c. Once you've done that, create a duplicate record detection rule that uses Meeting_UID__c and all the fields you entered IMA Duplicate into as the matching criteria.

  2. When you discover duplicate Meeting_UID__c have been entered, you'll want to use a for loop that substitutes the values in those records for the fields with the same values in your IMA Duplicate record. That will cause them to be removed by the duplicate record rules when they're created.

  3. The list or set of duplicate records you found from your query of the database needs to be passed to another method that performs an update on those records just as you would with a list from trigger.new except you only pass those specific records. I've normally only done this type of thing with related records. For that reason, you may need to use an @future method so they don't happen in the same context.

You would simply take the ids you've identified and pass them to a method inside your BeforeInsert code using something like:

UpdateDupeRecords UDR = new UpdateDupeRecords(trigger.newmap.get(DupeIds));

You'd create a new method that would look like:

private void UpdateDupeRecords(list<Event_Staging__c>Dupes){
   list<Event_Staging__c>toUpdate = new list<Event_Staging__c>();
   for(Event_Staging__c d:Dupes){
      e = new Event_Staging__c();
      e.Meeting_UID__c = d.Meeting_UID__c;
      e.field... = d.field....;

   Update toUpdate;

If the above causes you problems because of it being in the same execution context, remove the private, move it to a different class, and add @future notation to the method. You'll need to pass the Ids and other fields to it as strings or else JSONify them, and then call it as you did above.

If you only pass the Ids, you'll have a problem in that you won't have the other field references. That constraint would force you to either write them to a custom object for temporary storage or to custom settings for retrieval later. Doing either of those would solve the issue with just passing the ids which you'd then query in the @future method.

  • In EventmethodBefore method, I tried fetching all the trigger.new records whose MettingUid field value is alraedy present in SF. Then Tried to update them with the code using sobj. But duplicate record is being created.
    – Laxman
    Sep 13, 2016 at 13:10
  • You need to remove them from the before insert list. That's why a duplicate record is being created. They need to be updated separately.
    – crmprogdev
    Sep 13, 2016 at 13:12
  • How and where should I update the already exisitng record with new field values
    – Laxman
    Sep 13, 2016 at 13:13
  • 1
    You send the list of dupes to a separate class/method that does an upsert or update. It's called from your before update method.
    – crmprogdev
    Sep 13, 2016 at 13:14
  • 1
    @crmprogdev As far as I know...trigger.new is a read-only collection. You can't remove records from it. Have you gotten that to work somewhere? I'm pretty sure this is not how the platform works.
    – Adrian Larson
    Sep 13, 2016 at 14:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .