• niklasen
  • NEWBIE
  • 0 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

Hello,

 

We have a custom object named "Bidder & Contractors" which is linked to Opportunities via a Lookup relationship.

As we want to have Roll-up summary functionality on the opportunity counting the 'Bidders & Contractors' set to 'Won' we put in the below trigger.

 

It is working fine until you try to delete a 'Bidder & Contractor' entry, which gives the following error: 

 

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger OpportunityRollUpContractors caused an unexpected exception, contact your administrator: OpportunityRollUpContractors: execution of AfterDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.OpportunityRollUpContractors: line 6, column 1". 

 

Many thanks for your help! 

 

trigger OpportunityRollUpContractors on Bidder_Contractors__c (after delete, after insert, after update) {
 
    Set<id> OpportunityIds = new Set<id>();
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();
 
    for (Bidder_Contractors__c item : Trigger.new)
        OpportunityIds.add(item.Opportunity__c);
 
    if (Trigger.isUpdate || Trigger.isDelete) {
        for (Bidder_Contractors__c item : Trigger.old)
            OpportunityIds.add(item.Opportunity__c);
    }
 
    // get a map of the shipments with the number of items
    Map<id,Opportunity> opportunityMap = new Map<id,Opportunity>([select id, Contractor_Count__c from Opportunity where id IN :OpportunityIds]);
 
    // query the Opportunities and the related Competition items and add the size of the Competition items to the Opportunity's Contractor_Count__c
    for (Opportunity opp: [select Id, Name, Contractor_Count__c,(select id from Awarded_Contractors_Bidders__r WHERE Awarded__c ='Won') from Opportunity where Id IN :OpportunityIds]) {
        opportunityMap.get(opp.Id).Contractor_Count__c = opp.Awarded_Contractors_Bidders__r.size();
        // add the value/shipment in the map to a list so we can update it
        opportunitiesToUpdate.add(opportunityMap.get(opp.Id));
    }
 
    update opportunitiesToUpdate;
    
    }