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
Raj R.Raj R. 

How to use Apex Trigger to create OpportunityShare?

Hi,

I would like to create a trigger to create an OpportunityShare record for a particular user whenever a new Opportunity is created. The end goal is to create a trigger to automatically share all Opportunities when the Opportunities are created. Below is the logic I am using and the errors I am getting. I need help figuring out how I can create an OpportunityShare record via Apex Trigger. Any thoughts as to why I am getting the error?

Code:
List<OpportunityShare> oppShareList = new List<OpportunityShare>();

User usr = [Select Id, name from user limit 1];//i will be querying the user involved in real code

for(Opportunity opp : oppList) {
    OpportunityShare oppShare = new OpportunityShare();

    oppShare.OpportunityAccessLevel = 'Edit';
    oppShare.OpportunityId = opp.Id;
    oppShare.UserOrGroupId = usr.Id;
   oppShareList.add(oppShare);

}

insert oppShareList;
Error:
  • Variable does not exist: OpportunityAccessLevel
Best Answer chosen by Raj R.
Prabhat Kumar12Prabhat Kumar12
Hi,

Your code is working fine in my ORG. I would sugget you to make oppertunity private in sharing setting in setup if not set to private.

All Answers

Prabhat Kumar12Prabhat Kumar12
Hi,

Your code is working fine in my ORG. I would sugget you to make oppertunity private in sharing setting in setup if not set to private.
This was selected as the best answer
Raj R.Raj R.
Hi Prabhat,

Thank you for your time.

I have found the solution to be as you suggested to use the Salesforce out of the box Sharing Settings.
https://help.salesforce.com/apex/HTViewHelpDoc?id=managing_the_sharing_model.htm