0

I was doing some case study for learning Triggers and got a requirement like below

  • Once a new Opportunity is added, then the Manager of Opportunity Owner need to be attach in the Opportunity team with 'Sales manager' Role

I was able to write an After Trigger and working fine without setting 'Opportunity Access Level'.

trigger OppTrigger on Opportunity (after insert) {
    for(Opportunity newOpp:Trigger.new){
            Opportunity uv = [Select ID, Owner.ManagerID from Opportunity where Opportunity.Id = :newOpp.Id Limit 1];
            if(uv.Owner.ManagerId != NULL) {
                OpportunityTeamMember oppTeam    =  new OpportunityTeamMember();
                oppTeam.TeamMemberRole           =  'Sales Manager';
                oppTeam.UserId                   =  uv.Owner.ManagerID;
                //oppTeam.OpportunityAccessLevel = 'Read Only';
                oppTeam.OpportunityId            = newOpp.Id;
                system.debug(oppTeam);
                insert oppTeam;
            }
    }
}

I am getting a run time error as below if I try to set the 'Opportunity Access Level'. But without Trigger and via UI I can set this, can someone help me to understand it better?

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger OppTrigger caused an unexpected exception, contact your administrator: OppTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, Opportunity Access: bad value for restricted picklist field: Read Only: [OpportunityAccessLevel]: Trigger.OppTrigger: line 11, column 1

2 Answers 2

1

OpportunityTeamMember.OpportunityAccessLevel is not a writeable field. You will have to make use of Opportunity Share object to achieve this. Hence you need to use the below mentioned code to provide the access.

OpportunityTeamMember oppTeam =  new OpportunityTeamMember();
oppTeam.TeamMemberRole = 'Sales Manager';
oppTeam.UserId =  uv.Owner.ManagerID;
oppTeam.OpportunityId = newOpp.Id;
insert oppTeam;

//get all of the team members' sharing records

List<<OpportunityShare> OpportunityShare> shares = [SELECT Id, OpportunityAccessLevel, 
    RowCause FROM OpportunityShare WHERE 
    OpportunityId IN :SomeSetOfOpptyIds AND 
    RowCause = 'Team'];

// set all team members access to read/write
for (OpportunityShare share : shares)  {
    share.OpportunityAccessLevel = 'Edit';
}
update shares;

Also looks like your trigger code is not bulkified one. You will end up with Too many SOQL queries: 101 governor limit error since you are firing query within for loop which is not at all recommended.

Refer this link for more details.

1

Since OpportunityAccessLevel is a Restricted picklist.

Valid values are: Read, Edit.

For more details on Read Only is not supported error, refer [this][1] link.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .