+ Start a Discussion
Nitin SharmaNitin Sharma 

How to share a record with apex.?

scenario: owner of the record has changed to someone and get Read access to previous owner. My code below:
trigger ShareRecord on Opportunity (after update) {
List<Opportunity> opptylist = new List<Opportunity>();
    for(Opportunity oppty : trigger.new){
        if(oppty.OwnerId != trigger.oldMap.get(oppty.Id).OwnerId){
            OpportunityShare opptyshare = new OpportunityShare();
            opptyshare.UserorGroupId = trigger.oldMap.get(oppty.Id).OwnerId;
            opptyshare.ParentId = oppty.Id;
            opptyshare.AccessLevel = 'READ';
            
            opptylist.add(opptyshare);
        }
    }
    insert opptylist;
}

but didn't work.

Thanks,
Nitin
 
Ravi Dutt SharmaRavi Dutt Sharma
Hey Nitin,

I doubt that your code was even compiling. Please try below code and let me know if it works. Thanks.
 
trigger OpportunityTrigger on Opportunity (after update) {
    List<OpportunityShare> opptylist = new List<OpportunityShare>();
    for(Opportunity oppty : trigger.new){
        if(oppty.OwnerId != trigger.oldMap.get(oppty.Id).OwnerId){
            OpportunityShare opptyshare = new OpportunityShare();
            opptyshare.UserorGroupId = trigger.oldMap.get(oppty.Id).OwnerId;
            opptyshare.OpportunityId = oppty.Id;
            opptyshare.OpportunityAccessLevel = 'READ';
            opptylist.add(opptyshare);
        }
    }
    Database.insert(opptylist,false);
}


 
Nitin SharmaNitin Sharma
Hi ravi,
while using ur code through same error
line no 6 - Field not writeable: OpportunityShare.UserorGroupId
 
Ravi Dutt SharmaRavi Dutt Sharma
Its works seamlessly on my org. Are you using my code as it is or you have made some changes?
Nitin SharmaNitin Sharma
I am using same code, no chages in your code.