Changing owner overrides sharing

I have a case record which I have shared with few other users manually. But when owner of the case is changed/assigned to a sales rep then all those sharing goes away and default sharing applies. Has anybody faced similar issue. Any thoughts to resolve?

Answer

You can persist them through the use of asynchronous code; basically, we store the state of sharing before the ownership change, then restore it afterwards.

First, we need a utility class for the future method:

public with sharing class Persistence {
    @future
    public static void persistSharing(String ShareString) {
        CaseShare[] reasons = (CaseShare[])JSON.deserialize(shareString, CaseShare[].class);
        for(CaseShare reason: reasons)
            reason.Id = null;
        Database.insert(reasons, false);
    }
}

Then, we create a trigger:

trigger CopyShare on Case (before update) {
    Set<Id> caseIds = new Set<Id>();
    for(Case record: Trigger.new)
        if(record.OwnerId != Trigger.oldMap.get(record.Id).OwnerId)
            caseIds.add(record.Id);
    Persistence.persistSharing(
        JSON.serialize(
            [SELECT Id, CaseAccessLevel, CaseId, RowCause, UserOrGroupId 
             FROM   CaseShare 
             WHERE  CaseId IN :caseIds AND 
                    RowCause = 'Manual']));

}

Note that we can only back up and restore manual shares. Other types of shares, such as from sharing rules or teams, are managed by the system.

Attribution
Source : Link , Question Author : doga , Answer Author : sfdcfox

Leave a Comment