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
DhairyaDhairya 

Apex after Insert Trigger

Hi,

 

   Here i would likek to update test1__c value with related objects fields. But it didn't work at all.

 

 

 

trigger budTotalTrigger on Budget__c (after insert) {
   list <projects__c> projects = [select id,name,test1__C from Projects__C];
   
   for(budget__C bud : trigger.new)
   {
     for(projects__c pro : projects) 
     {
       if(pro.id == bud.PMO_Project__r.id)
       {
        pro.test1__c = pro.test1__C + bud.value__c;
      
       }
      database.update(pro);
    
     }
     
        
  
   }
}

 

 

WizradWizrad

Couple things about this.

 

1) Please be more specific than "it didn't work at all".

2) NEVER put DML in loops.

 

Below is a more efficient solution.

 

 

trigger budTotalTrigger on Budget__c (after insert) {
   //If you have > 50k projects in your org the trigger would fail
   Map<Id, Double> projectIdToBudValue = new Map<Id, Double>();
   for(Budget__c bud : Trigger.new) {
     projectIdToBudValue.put(bud.PMO_Project__c, bud.Value__c);
   }
   
   list <projects__c> projects = [select id,name,test1__C from Projects__c WHERE Id in :projectIdToBudValue.keySet()];
   
   for(projects__c pro : projects) {
     pro.test1__c += projectIdToBudValue.get(pro.Id); 
   }

   update projects;
}

 

 

DhairyaDhairya

Hey Sorry,

  for not being clear and specific in question. I tried following code but its not updating test1__c field on projects__c field.

 

  Scenario is

 

  (1) I am creating Budget record with the help of VF page and Extension

 

  (2) Then i am using Trigger to update budget related project filed test1__c with budget value__c.

 

      [ So, it may happened that there are more than one budget for single project and test1__C is accumulated value ]

 

Appreciate your help

 

thanks,

Dhairya