Trigger to update parent object value with child value

In my company we are using Oppotunity standard object and we have created a custom Quote object. The opportunity object is the parent and Quote is the child. How has to be the trigger in order to update the Amount Opportunity value with the Amount Quote Value?

I´m new with Apex and it will be very usefull has some APEX code to do this.

I have reuse some trigger example and it has to be something similar to:

trigger UpdateAmount on Quote__c (after insert) {

    List<Opportunity> parentObjList = new List<Opportunity>();
    List<Id> listIds = new List<Id>();

    for (Quote__c childObj : Trigger.new {
        listIds.add(childObj.Opportunity);
    }

    parentObjList = [SELECT id,Name,(SELECT ID, Total_List_Price__c FROM Quote__r) FROM Opportunity WHERE ID IN :listIds];

    for (Opportunity opp : parentObjList){
        for (Quote__c quote: Opportunity.Quote__r){
            opp.Amount = quote.Total_List_Price__c;
        {
     {

    update parentObjectList;
}

Thanks

Answer

Just looking at the code you have there a few things stand out.
I haven’t tested this but I’ve added comments which might help you along

trigger UpdateAmount on Quote__c (after insert, after update) { //You want it on update too, right?
  Map<ID, Opportunity> parentOpps = new Map<ID, Opportunity>(); //Making it a map instead of list for easier lookup
  List<Id> listIds = new List<Id>();

  for (Quote__c childObj : Trigger.new {
    listIds.add(childObj.Opportunity);
  }

  //Populate the map. Also make sure you select the field you want to update, amount
  //The child relationship is more likely called Quotes__r (not Quote__r) but check
  //You only need to select the child quotes if you are going to do something for example checking whether the quote in the trigger is the latest
  parentOpps = new Map<Id, Opportunity>([SELECT id, amount Name,(SELECT ID, Total_List_Price__c FROM Quotes__r) FROM Opportunity WHERE ID IN :listIds]);

  for (Quote__c quote: Trigger:new){
     Opportunity myParentOpp = parentOpps.get(quote.Opportunity__c);
     myParentOpp.Amount = quote.Total_List_Price__c;
  }

  update parentOpps.values();
}

Attribution
Source : Link , Question Author : Guillermo , Answer Author : Doug B

Leave a Comment