Skip to main content
Hi,

We're new to Salesforce Development but we've managed to pull together a trigger that updates a Primary Contact Lookup on the opportunity. The trigger works perfectly well, however, we hit the SQL limit in Salesforce and are unsure how to overcome this.

Please can you advise on how the code could be written in a more efficient way?

 

trigger trgMnCopyPrimaryContact on Opportunity (before update) {

for (Opportunity o : Trigger.new) {

OpportunityContactRole[] contactRoleArray =

[select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];

if (contactRoleArray.size() > 0) {

o.Opportunity_contact__c = contactRoleArray[0].ContactID;

}else{

o.Opportunity_contact__c = null;

}

}

}

Thanks,

Kev

 
6 respuestas
  1. 21 mar 2016, 14:06

    Please try below code.

    trigger trgMnCopyPrimaryContact on Opportunity (before update)

    {

    Set<ID> setOpp = new Set<ID>();

    for (Opportunity o : Trigger.new)

    {

    setOpp.add(o.id);

    }

    List<OpportunityContactRole> lstOppContRole = [ select Id , ContactID, isPrimary ,OpportunityId

    from OpportunityContactRole

    where OpportunityId in :setOpp

    ORDER BY isPrimary DESC, createdDate

    ];

    Map<ID,OpportunityContactRole> MapOppWiseOppContRole = new Map<ID,OpportunityContactRole>();

    for(OpportunityContactRole oppContRole : lstOppContRole )

    {

    if( MapOppWiseOppContRole.containsKey( oppContRole.OpportunityId ) == false )

    {

    MapOppWiseOppContRole.put( oppContRole.OpportunityId , oppContRole );

    }

    }

    for ( Opportunity o : Trigger.new )

    {

    if( MapOppWiseOppContRole.containsKey( o.id ) )

    {

    OpportunityContactRole oppContRole = MapOppWiseOppContRole.get( o.id );

    o.Opportunity_contact__c = oppContRole.ContactID;

    }

    else

    {

    o.Opportunity_contact__c = null ;

    }

    }

    }

    Let us know if that wll help you

     
0/9000