Recently, I was working on an assignment, where I had to create Opportunity Team Member records in a trigger on some user action. But when I started to write the code and tried saving it, I got the error “Field is not writeable: OpportunityTeamMember.OpportunityAccessLevel“. Uuuhhh.. I got stuck! According to the documentation this field is writable, then why not for me. Below is the code that I tried, and came to know, that OpportunityAccessLevel field not writable in Apex.
OpportunityTeamMember OppTeamMember = new OpportunityTeamMember(); OppTeamMember.UserId = UserInfo.getUserId(); OppTeamMember.OpportunityId = opp.Id; OppTeamMember.OpportunityAccessLevel='Edit'; OppTeamMember.TeamMemberRole = 'Opportunity Team Member';
The above code gave me the error:
“Field is not writeable: OpportunityTeamMember.OpportunityAccessLevel“
This error doesn’t occur when you create opportunity team member by going to the related list on the opportunity. You can give any access level from there.
After spending some time, I figured out and came to know, that: If Opportunity sharing settings are set to Private, then you can not write this field OpportunityAccessLevel. This field will be set to Read Only by default.
But my requirement was to give “Edit” access to opportunity team member while creating. So the workaround I opted was:
- Create opportunity team member record first, Salesforce will give READ permission by default.
- Then, give edit access using the OpportunityShare object because as soon as you create an OpportunityTeamMember record, Salesforce creates an entry in sharing records for that opportunity and user.
- Query the sharing record that Salesforce created just now, and update the access level to EDIT.
Here is the code:
OpportunityTeamMember OppTeamMember = new OpportunityTeamMember(); OppTeamMember.UserId = UserInfo.getUserId(); OppTeamMember.OpportunityId = opp.Id; //OppTeamMember.OpportunityAccessLevel='Edit'; OppTeamMember.TeamMemberRole = 'Opportunity Team Member'; insert OppTeamMember; //get all of the sharing records which Salesforce created right now. rowCause is Sales Team. List<OpportunityShare> oppShareRecords = [select Id, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId =: opp.Id and RowCause = 'Sales Team']; // set all team members access to read/write for (OpportunityShare OppShare : oppShareRecords){ OppShare.OpportunityAccessLevel = 'Edit'; } update oppShareRecords;
Good Luck and Happy Coding !!
Recent Comments