function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pranil SarodePranil Sarode 

Field is not writeable: OpportunityShare.UserOrGroupId

trigger opptyShareTrig on Opportunity (after insert) {
      List<OpportunityShare> share=new List<OpportunityShare>();
      User u=[select id from User where alias='knair'];
      for(Opportunity op:Trigger.New){
            if(op.stageName=='Closed Won'){
                        OpportunityShare os=new OpportunityShare();
                        os.OpportunityId=op.id;
                        os.UserOrGroupId=u.id;
                        os.OpportunityAccessLevel='Edit';
                        os.RowCause='Manual';
                        share.add(os);
            }
      }
    insert share;
  }


Getting Error
Best Answer chosen by Pranil Sarode
Deepali KulshresthaDeepali Kulshrestha
Hi Pranil,
Greetings to you!

- Please use the code {Solved} : -
 
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 the below link for further reference : - 
https://salesforce.stackexchange.com/questions/15227/why-i-am-getting-field-is-not-writable-opportunityshare-userorgroupid-compile
    
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com