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
MohiniMohini 

Please help me with an apex trigger handler for the scenarion -

1.If opportunity record is closed dont make any change 
2. Opportunity is parent and sub object is child (lookup). Once any of the sub record stage is closed won , the field of sub (Revenue , cost and probability) gets copied to the parent opportunity
Arun Kumar 1141Arun Kumar 1141

Hi Mohini

Considering Sub as a custom object and (Revenue , cost and probability) fields on boththe object.

trigger CopyFieldsToOpportunity on Sub__c (after update) {
    Set<Id> opportunityIds = new Set<Id>();
    for (Sub__c sub : Trigger.new) {
        if (sub.Stage__c == 'Closed Won') {
            opportunityIds.add(sub.Opportunity__c);
        }
    }

    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>([
        SELECT Id, Revenue__c, Cost__c, Probability__c
        FROM Opportunity
        WHERE Id IN :opportunityIds
    ]);

    for (Sub__c sub : Trigger.new) {
        if (sub.Stage__c == 'Closed Won') {
            for (Opportunity opportunity : opportunitiesToUpdate) {
                if (opportunity.Id == sub.Opportunity__c) {
                    opportunity.Revenue__c = sub.Revenue__c;
                    opportunity.Cost__c = sub.Cost__c;
                    opportunity.Probability__c = sub.Probability__c;
                }
            }
        }
    }

    if (!opportunitiesToUpdate.isEmpty()) {
        update opportunitiesToUpdate;
    }
}
 

 

Please mark this as best answer!!