function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DJ 367DJ 367 

trigger works fine for single record but not for data loader

Hello All,

I have a trigger which works fine for single record but does not work properly for while updating record thru data loader, can someone please help me to fix this.

Thanks
trigger NumberOfContRole1 on Opportunity (before update,before insert) {

    List<OpportunityContactRole> contactRolesList = [SELECT Id from OpportunityContactRole  where OpportunityId in :Trigger.new];
    system.debug('*****contactRolesList : ' + contactRolesList);
     List<Id> lstOcr = new  List<Id>();
     
    for(OpportunityContactRole OCR :contactRolesList){
        lstOcr.add(OCR.Id);
    }
    
    system.debug('*****lstOcr : ' + lstOcr);
    
    for(opportunity op : trigger.new){
        if(!lstOcr.isEmpty()){
            system.debug('*****lstOcr.size() : ' + lstOcr.size());
            op.NoOfContactRole__c= lstOcr.size();
            system.debug('*****op.NoOfContactRole__c: ' + op.NoOfContactRole__c);
        }
    } 
}

 
Dhanya NDhanya N
Hi DJ,

What is the error you are getting when you update the record though data loader?

 
DJ 367DJ 367
Hi Dhanya,

It is updating  NoOfContactRole__c field with same value for all the opportunity. where requirment is to update NoOfContactRole against the opportunity. thanks
 
gpforcegpforce
Hi DJ,

This is something like having a custom roll up summary field.

Your code is working for single record because it fetches the oppotunity contact role records for single opportunity while with multiple records in data loader, you are getting the contact role records for all opportunities.

You may try using an inline query something like below:

trigger NumberOfContRole1 on Opportunity (before update,before insert) {
   // Confirm child relationship name of oppotunity contact role
    List<Opportunity> opptyList = [SELECT Id, (SELECT Id from OpportunityContactRoles) from opportunity where OpportunityId in :Trigger.new];
    for(opportunity op : trigger.new){
            op.NoOfContactRole__c= op.OpportunityContactRoles.size();
            system.debug('*****op.NoOfContactRole__c: ' + op.NoOfContactRole__c);
    }
}

Hope this works. Please mark as best answer if it does.