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
Abhilash DaslalAbhilash Daslal 

After Insert Trigger not getting invoked

Hi ,
I have written a simple after insert trigger on Account such that for every new Account created, a new related Opportunity is created.

But the trigger is not getting invoked.Any ideas why this may be happening

trigger CreateNewAccountOpportunity on Account (after insert) {

    List<Opportunity> oppList = new List<Opportunity>();
    for(Account acc : Trigger.new){
        Opportunity opp = new Opportunity();
        opp.Name = acc.Name;
        opp.StageName = 'Proposal';
        opp.CloseDate = System.today() + 30;
        oppList.add(opp);
    }
    System.debug('@@@---->'+Trigger.new);
       System.debug('oppList---->'+oppList); 
    
    if(oppList.isEmpty() == false){
        Database.insert(oppList);
    }
}
Ajay K DubediAjay K Dubedi
Hi Abhilash,
Your code is working properly you just have to check, is there any validation rule or trigger was written in your org that affect the creation of Opportunity.
And put your code in the try-catch block for find Exception.
And always try to do separate trigger and it's handler class as below:
Trigger:
trigger CreateNewAccountOpportunity on Account (after insert) {
    if(trigger.IsInsert && trigger.IsAfter) {
        CreateNewAccountOpportunity_handler.createOpportunity(trigger.new);
    }
}

Handler:
public class CreateNewAccountOpportunity_handler {
    public static void createOpportunity(List<Account> accList) {
        try {
            if(accList.size() > 0) {
                List<Opportunity> oppList = new List<Opportunity>();
                for(Account acc : accList){
                    Opportunity opp = new Opportunity();
                    opp.Name = acc.Name;
                    opp.StageName = 'Proposal';
                    opp.CloseDate = System.today() + 30;
                    oppList.add(opp);
                }
                if(oppList.isEmpty() == false){
                    Database.insert(oppList);
                }
            }
        } 
        catch(Exception e)
        {
            system.debug('->>'+e.getCause() + '->>' + e.getLineNumber() + '->>' + e.getMessage());
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
yogesh_patilyogesh_patil
Hi Abhilash,

Firstly make sure your trigger is active.
Secondly,  Add the below line in the opporttunity creation block.

opp.Id = acc.Id;
Andrew GAndrew G
        opp.AccountId = acc.id;


Yogesh was very close.  There is no association between the Account and the Opportunity.

Regards
Andrew