1

I am trying to update a custom field on Opportunity record with number of Opportunity Contact Role records and this field value will be used in Validation rule on Opportunity. It's very simple trigger and was working before. Now in order to bulkify, I was changing the code and now the update is not at all working. I can see the record count when I write using System.debug statement, but same value is not getting updated on Oppr field. I might be doing a silly mistake, but not able to figure out. Please help.

trigger OpportunityTrigger on Opportunity (before update)
{
    for(Opportunity opp: [select Id,Number_of_Contacts_Roles_Assigned__c, (SELECT Id, Role FROM OpportunityContactRoles) FROM Opportunity WHERE Id IN :Trigger.new])
    {
        Integer iCount = 0;
        iCount = opp.OpportunityContactRoles.size();
        opp.Number_of_Contacts_Roles_Assigned__c = iCount;
      }
}

1 Answer 1

3

You need to update the records in Trigger.new. The easiest fix is simply:

trigger OpportunityTrigger on Opportunity (before update)
{
    for(Opportunity opp: [select Id,Number_of_Contacts_Roles_Assigned__c, (SELECT Id, Role FROM OpportunityContactRoles) FROM Opportunity WHERE Id IN :Trigger.new])
    {
        Integer iCount = 0;
        iCount = opp.OpportunityContactRoles.size();
        Trigger.newMap.get(opp.Id).Number_of_Contacts_Roles_Assigned__c = iCount;
      }
}

However, this is inefficient; just use an aggregate query instead:

trigger OpportunityTrigger on Opportunity (before update)
{
    Map<Id, AggregateResult> contactRoles = new Map<Id, AggregateResult>([
        SELECT OpportunityId Id, COUNT(ID) roles
        FROM OpportunityContactRole
        WHERE OpportunityId = :Trigger.new
        GROUP BY OpportunityId
    ]);
    for(Opportunity record: Trigger.new) {
        AggregateResult result = contactRoles.get(record.Id);
        if(result == null) {
            record.Number_of_Contacts_Roles_Assigned__c = 0;
        } else {
            record.Number_of_Contacts_Roles_Assigned__c = (Integer)result.get('roles');
        }
    }
}
1
  • Thank you so much, it fixed my issue. I will try to search and understand about 'AggregateResult' object.
    – Amulya
    Jun 17, 2020 at 22:13

You must log in to answer this question.

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