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
Rory McDonnellRory McDonnell 

Opportunity not being associated with Account?

Hi I have created the following Trigger that creates ten opportunities when an account has more than 99 employees. It is working as expected and the opps are being created, only issue is that they are not being linked to the account record. Any idea why that is the case?
 
trigger CreateTenOpps on Account (before insert, before update) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 99) {
            for (Integer i = 0; i < 10; i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', 
                                                  Name = 'Trigger Opp',
                                                  AccountId = acc.Id);
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
Hi Rory,
Before update will work, but it is recommended to work on After trigger events when you are working on other related/un-related records.

All Answers

Danish HodaDanish Hoda
Hi Rory,
You need to use After events on the trigger.You will not be able to get Account Id in before Insert.
Rory McDonnellRory McDonnell
Hi Danish, I would expect that to be the case for new accounts but wouldn't existing accounts that I am updating already have an ID?

Would it be an 'After insert, before update' trigger then?
Maharajan CMaharajan C
It should be After Insert.

trigger CreateTenOpps on Account (after insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 99) {
            for (Integer i = 0; i < 10; i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', 
                                                  Name = 'Trigger Opp',
                                                  AccountId = acc.Id);
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

Thanks,
Maharajan.C
Danish HodaDanish Hoda
Hi Rory,
Before update will work, but it is recommended to work on After trigger events when you are working on other related/un-related records.
This was selected as the best answer