[SalesForce] Why i am getting “Field is not writable: OpportunityShare.UserOrGroupId” compile time error

I am getting compile time error while trying to assign userId to opShare.UserOrGroupId field. I am not sure what is wrong in it –

    List<OpportunityShare> grantAccessUpsertLst = new List<OpportunityShare>(); 
    for(String userId : userIds){
            List<UserRecordAccess> userRecords = [SELECT RecordId, HasEditAccess FROM UserRecordAccess WHERE UserId =: userId AND RecordId =: oppId];
            if(userRecords.size() > 0 && !(userRecords.get(0).HasEditAccess)){
                OpportunityShare opShare = new OpportunityShare();
                opShare.UserOrGroupId = userId; // Error Line
                opShare.OpportunityAccessLevel = ACCESS_LEVEL_EDIT;
                opShare.OpportunityID = oppId;
                grantAccessUpsertLst.add(opShare);          
            }
    }
    if(grantAccessUpsertLst.size() > 0)
        upsert grantAccessUpsertLst;

Thanks in advance

Best Answer

List<OpportunityShare> grantAccessUpsertLst = new List<OpportunityShare>(); 
for(String userId : userIds){
        List<UserRecordAccess> userRecords = [SELECT RecordId, HasEditAccess FROM UserRecordAccess WHERE UserId =: userId AND RecordId =: oppId];
        if(userRecords.size() > 0 && !(userRecords.get(0).HasEditAccess)){
            OpportunityShare opShare = new OpportunityShare();
            opShare.UserOrGroupId = userId; // Error Line
            opShare.OpportunityAccessLevel = ACCESS_LEVEL_EDIT;
            opShare.OpportunityID = oppId;
            grantAccessUpsertLst.add(opShare);          
        }
}
if(grantAccessUpsertLst.size() > 0)
    insert grantAccessUpsertLst;//Use Insert instead of upsert

You can use insert to share opportunity share. Also if you want to update any share records you will need to first delete the existing share records for the user and insert the new one. Hope this helps.

Related Topic