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
Russell baker 1Russell baker 1 

Trigger for field update on related object based on opportunity stage

I created a custom object budget and create a lookup relationship with opportunity. So one budget lookup field on opportunity and update this field according to close date via trigger. If close date within month of Jan so budget field update as “Jan”. So all Jan close date opportunity come under Jan budget.
 
My requirement is when any opportunity stage change as close won so opportunities amount should be some and populate on custom field “won amount “ on budget object. Same with open opportunities all open opportunities amount should show on “pipeline amount” custom field.   
I think trigger would be good approach but I don’t know how to query. Could you experts help me?
User-added image
AshlekhAshlekh
Hi,

You need to write a trigger on opporunity. I've written a trigger for your requirement but you need to imporve my code can need to change the field name with original fields.
 
trigger updateField on Opportunity (after update) {

    Map<Id,Decimal>  budgetIDTotalMap = new MAp<Id,Decimal>();  
    for (Opportunity opp : Trigger.new)
    {
          if(opp.stageName == 'ClosedWon'){
            Decimal t = 0;
            if(budgetIDTotalMap.containsKey(opp.budget__c) && budgetIDTotalMap.get(opp.budget__c) != null)
                   t = budgetIDTotalMap.containsKey(opp.budget__c);
                budgetIDTotalMap.put(opp.budget__c,t+opp.amount);
           }
    }

//Now query your all budget object record and update the values
List<Budget__c> blist = [select id,won_amount__c from budget__c where id in :budgetIDTotalMap.keySet()];
for(Budget__c c: blist)
{
    if(budgetIDTotalMap.containskey(c.id))
    {
      c.won_amount__c += budgetIDTotalMap.get(c.id);
    }
}

   if(blist.size()>0)
   update blist;
}

-Thanks
Ashlekh Gera
Russell baker 1Russell baker 1
Hi getting error :
Compile Error: Illegal assignment from Boolean to Decimal at line 9 column 20