1

I have the following Apex Trigger that is set to auto-create a custom child object (Onboarding) when a specific field on the opportunity child object (Stage) is set to Closed Won. This trigger is working as I want it to but I now need to have it carry additional fields of data from both the account parent object and from the opportunity child object.

Where in this trigger would I append lines for carrying data over and how is it written out in this formatting? To make the answer more straight forward, lets say I want the name of the Onboarding page to be the same as the name of the Opportunity and the field from the Account object (Billing_Address) to carry over to the Onboarding object under its field for billing address.

trigger CreateOB on Opportunity (after insert, after update) {
    Onboarding__c[] inserts = new Onboarding__c[] {};
    for (Opportunity a : Trigger.new) {
        if (a.StageName == 'Closed Won') {
            Opportunity old = Trigger.oldMap.get(a.Id);
            if (a.StageName != old.StageName) {
                inserts.add(new Onboarding__c(Account_Name__c = a.AccountId));
            }
        }
    }
    insert inserts;
}

Thanks in advance! Any and all help is greatly appreciated while still getting the ropes of these triggers.

1 Answer 1

3

Information not directly on the Opportunity is not automatically available so you have two options...

One: Create formula fields on the Opportunity to get the information from Account then simply use those fields to directly populate the info on the new on boarding record.

Two: Or via code - Querying for the Opportunity and related Account fields:

trigger CreateOB on Opportunity (after insert, after update) {
    Onboarding__c[] inserts = new Onboarding__c[] {};
    for (Opportunity o : [
            Select StageName, Name, AccountID, Account.BillingStreet
            From Opportunity
            Where ID IN :trigger.new
            ])) {
        if (o.StageName == 'Closed Won') {
            Opportunity old = Trigger.oldMap.get(o.Id);
            if (o.StageName != old.StageName) {
                inserts.add(new Onboarding__c(
                        Account_Name__c = o.AccountId,
                        Name = o.Name,
                        BillingAddress__c = o.Account.BillingStreet
                        ));
            }
        }
    }
    insert inserts;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .