+ Start a Discussion
Rohit SrivastavaRohit Srivastava 

Need Urgent Help on Record Unfollow through Apex

I have a requirement where I need to make the owner follow a record based on certain conditions. Now when I change the owner, the new owner should automatically follow the record. However the code I have written is making both the old and new owner follow the record. How to make the the old owner unfollow the record? 
Below is the piece of code I have written and I am calling this method from trigger on after insert and after update:

public static String doFollowRecord(List<Opportunity> opportunities, Map<Id, Opportunity> oldMap, Map<Id, Opportunity> newMap) {
        String errMsg;
        if(isInsert){
        for (Opportunity opp : opportunities) {
            if (opp.RecordTypeId == opportunityRecordTypeNameToIdMap.get(RENEWALRECORDTYPE.toLowerCase()) && opp.Managed_Opportunity__c ==True) {
                EntitySubscription follow = new EntitySubscription (
                                         parentId = opp.id,
                                         subscriberid =opp.ownerid);
                insert follow;
            }
                                                }
                                }  
        return errMsg;
    }


Need urgent help on this.
Best Answer chosen by Rohit Srivastava
Arunkumar RArunkumar R
Hi Rohit,

Here is the Complete Code with Bulikified Support, Add you condition in the below class if you want, This is a generic trigger,

Trigger:
trigger FollowRecordOpportunityTrigger on Opportunity (after insert, after update)
{
    if(Trigger.isInsert)
    {
        FollowRecordHandler.followRecord(Trigger.newMap, null, 'insert');
    }
    if(Trigger.isUpdate)
    {
        FollowRecordHandler.followRecord(Trigger.newMap, Trigger.oldMap, 'update');
    }
}

Apex Class:
 
public class FollowRecordHandler
{
    public static void followRecord(Map<Id, Opportunity> newOppMap, Map<Id, Opportunity> oldOppMap, String operation)
    {
        List<EntitySubscription> entitySubToBeInsert = new List<EntitySubscription>();
        List<Id> entitySubIdsToBeDelete = new List<Id>();
        
        if(operation.equalsIgnoreCase('insert'))
        {
            for(Opportunity currOpp : newOppMap.values())
            {
                // Add your condition with if statement
                EntitySubscription follow = new EntitySubscription(parentId = currOpp.id, subscriberid =currOpp.ownerid);
                entitySubToBeInsert.add(follow);
            }
            
        }
        
        else if(operation.equalsIgnoreCase('update'))
        {
            for(Opportunity currOpp : newOppMap.values())
            {
                if(oldOppMap.get(currOpp.Id).OwnerId != currOpp.OwnerId)
                {
                    EntitySubscription follow = new EntitySubscription(parentId = currOpp.id, subscriberid =currOpp.ownerid);
                    entitySubToBeInsert.add(follow);
                    
                    entitySubIdsToBeDelete.add(oldOppMap.get(currOpp.Id).OwnerId);
                }
            }
        }
        
        if(!entitySubToBeInsert.isEmpty())
        {
            insert entitySubToBeInsert;
        }
        
        if(!entitySubIdsToBeDelete.isEmpty())
        {
            List<EntitySubscription> entitySubDelete = new List<EntitySubscription>();
            for(EntitySubscription currEntity : [select id from EntitySubscription where subscriberid =:entitySubIdsToBeDelete])
            {
                EntitySubscription ent = new EntitySubscription();
                ent.ID = currEntity.Id;
                entitySubDelete.add(ent);
            }
            
            Delete entitySubDelete;
        }
    }
}

Mark this as a best answer, if this solution helpful to you...!

All Answers

Grazitti TeamGrazitti Team
Hi Rohit,

I glad to help you.

To achiive this. We have to fire the trigger in two conditions:
  1. After Insert: In this, We have to insert the record in the EntitySubscription object as you have mentioned in the thread.
  2. After Update: In this, We should insert the record in the EntitySubscription object for the new owner and delete a record for the older owner.
Here is the sample code for the "2" point:

SOQL for delete a record: 
[select id from EntitySubscription where subscriberid =:[oldOpp.id] LIMIT 49000];
I would like to give one suggest to write the trigger in a best way that you should use the factory class. Please find the link here - http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

Please Mark this as Best Answer if it helps you

Regards,
Grazitti Team
Web: www.grazitti.com
Email: sfdc@grazitti.com
Arunkumar RArunkumar R
Hi Rohit,

Here is the Complete Code with Bulikified Support, Add you condition in the below class if you want, This is a generic trigger,

Trigger:
trigger FollowRecordOpportunityTrigger on Opportunity (after insert, after update)
{
    if(Trigger.isInsert)
    {
        FollowRecordHandler.followRecord(Trigger.newMap, null, 'insert');
    }
    if(Trigger.isUpdate)
    {
        FollowRecordHandler.followRecord(Trigger.newMap, Trigger.oldMap, 'update');
    }
}

Apex Class:
 
public class FollowRecordHandler
{
    public static void followRecord(Map<Id, Opportunity> newOppMap, Map<Id, Opportunity> oldOppMap, String operation)
    {
        List<EntitySubscription> entitySubToBeInsert = new List<EntitySubscription>();
        List<Id> entitySubIdsToBeDelete = new List<Id>();
        
        if(operation.equalsIgnoreCase('insert'))
        {
            for(Opportunity currOpp : newOppMap.values())
            {
                // Add your condition with if statement
                EntitySubscription follow = new EntitySubscription(parentId = currOpp.id, subscriberid =currOpp.ownerid);
                entitySubToBeInsert.add(follow);
            }
            
        }
        
        else if(operation.equalsIgnoreCase('update'))
        {
            for(Opportunity currOpp : newOppMap.values())
            {
                if(oldOppMap.get(currOpp.Id).OwnerId != currOpp.OwnerId)
                {
                    EntitySubscription follow = new EntitySubscription(parentId = currOpp.id, subscriberid =currOpp.ownerid);
                    entitySubToBeInsert.add(follow);
                    
                    entitySubIdsToBeDelete.add(oldOppMap.get(currOpp.Id).OwnerId);
                }
            }
        }
        
        if(!entitySubToBeInsert.isEmpty())
        {
            insert entitySubToBeInsert;
        }
        
        if(!entitySubIdsToBeDelete.isEmpty())
        {
            List<EntitySubscription> entitySubDelete = new List<EntitySubscription>();
            for(EntitySubscription currEntity : [select id from EntitySubscription where subscriberid =:entitySubIdsToBeDelete])
            {
                EntitySubscription ent = new EntitySubscription();
                ent.ID = currEntity.Id;
                entitySubDelete.add(ent);
            }
            
            Delete entitySubDelete;
        }
    }
}

Mark this as a best answer, if this solution helpful to you...!
This was selected as the best answer
Rohit SrivastavaRohit Srivastava
Thanks a lot for your help!!