You should leverage Case Team functionality.
Basically, whenever Case ownership changes you should add the user to a case team as member and provide read/write access to that user.
Here is the logic:
- Define case team role.
- If previous case owner ownerId and new OwnerId are not same then add the user in the team. Also, put a check that, previous owner is a user and not a queue.
- Also verify that user is not previously exist as case team member of that case.
Refer this below code and use this in
after update trigger.
public void addCaseTeamMembersToCase(List<Case> lstNewCases, Map<Id,Case> mapOldCases)
String oldOwnerId = mapOldCases.get(objCase.Id).ownerId;
String newOwnerid = objCase.ownerId;
&& oldOwnerId.subString(0,3) == '005')
//verify if the oldOwnerId ever exists as Case Team members
List<CaseTeamMember> lstCaseTeamMember = [SELECT MemberId FROM CaseTeamMember
WHERE ParentId =: objCase.Id
AND MemberId =: oldOwnerId];
if(lstCaseTeamMember.size() == 0)
ParentId = objCase.Id,
MemberId = oldOwnerId
objCaseTeamRole = [SELECT Id
WHERE Name = '<my team role>' LIMIT 1];
for (CaseTeamMember objCaseTeamMember : mapMembersToAdd.values())
objCaseTeamMember.TeamRoleId = objCaseTeamRole.Id;