Need help in Optimizing below code.

Requirement is to update "opportunity shared" checkbox on "Opportunity" object whenever opportunity is un-shared. (Delete trigger on "Opportunityteammember" object).

 trigger SharedOpportunity on OpportunityTeamMember (after delete) {

 List<Id> idOpp = new List<Id>();
 List<Opportunity> OpportunityToUpdate = new List<Opportunity>();

    if(trigger.isDelete) {

        for (OpportunityTeamMember op : trigger.old) {


    if(idOpp.isEmpty()) return;

    for(Id id : idOpp) {

        Opportunity opportunity = new Opportunity(Id = id);
        opportunity.Opportunity_Shared__c  = false;



    if(OpportunityToUpdate.size() > 0)


Your trigger will fail any time there is more than one OpportunityTeamMember on a record. It'll update the Opportunity.Opportunity_Shared__c field to false even when there is still an OpportunityTeamMember present other than the one deleted.

You'd need to perform a query before you decide which records to update. One approach would run roughly like this:

for (OpportunityTeamMember op : Trigger.old) {

for (Opportunity o : [SELECT Id, (SELECT Id FROM OpportunityTeamMembers) FROM Opportunity WHERE Id IN :idOpp]) {
    if (o.OpportunityTeamMembers.size() == 0) {
        opportunitiesToUpdate.add(new Opportunity(Id = o.Id, Opportunity_Shared__c = false));

update opportunitiesToUpdate;

Your code as written is a bit "wordy". It's not terribly inefficient, but you could easily compress it in a way similar to the above and remove the unnecessary if checks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.