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
hybin joseph 2hybin joseph 2 

I have just started off learning triggers and I wrote a trigger but it is not working please help...

I have just started off learning triggers and I wrote a trigger but it is not working.Please find the trigger I wrote below.Let me know what is wrong on this one :

trigger OpportunityCreator on Account (After Insert) {

list<Opportunity> LstOpps = new list<Opportunity>();

for(Account acct : Trigger.new){
Opportunity Opps = new Opportunity();
Opps.StageName = 'Open';
Opps.Name = 'New Opportunity';
Opps.CloseDate = Date.newinstance(2017,02,21);
LstOpps.add(Opps);



Insert LstOpps;

}

 
Best Answer chosen by hybin joseph 2
Dayakar.DDayakar.D
Hi,

Your trigger is working fine, but the problem is you are not relating the new inserted opportunity with Account
Please try below code 
trigger OppCreation on Account (After insert) {
    list<Opportunity> LstOpps = new list<Opportunity>();
    
    for(Account acct : Trigger.new){
        Opportunity Opps = new Opportunity();
        Opps.StageName = 'Open';
//Your are not Relating account with Opportunity in your trigger
        Opps.AccountId=acct.Id;
        Opps.Name = 'New Opportunity';
        Opps.CloseDate = Date.newinstance(2017,02,21);
        LstOpps.add(Opps);
        
        
    } 
    Insert LstOpps;
    
}

Let me know, if it works,

Best Regards,
Dayakar

All Answers

Dayakar.DDayakar.D
Hi,

Your trigger is working fine, but the problem is you are not relating the new inserted opportunity with Account
Please try below code 
trigger OppCreation on Account (After insert) {
    list<Opportunity> LstOpps = new list<Opportunity>();
    
    for(Account acct : Trigger.new){
        Opportunity Opps = new Opportunity();
        Opps.StageName = 'Open';
//Your are not Relating account with Opportunity in your trigger
        Opps.AccountId=acct.Id;
        Opps.Name = 'New Opportunity';
        Opps.CloseDate = Date.newinstance(2017,02,21);
        LstOpps.add(Opps);
        
        
    } 
    Insert LstOpps;
    
}

Let me know, if it works,

Best Regards,
Dayakar
This was selected as the best answer
hybin joseph 2hybin joseph 2
Thanks Dayakar I added that and now I can see my Opps being linked to acct.I saw the other Opps as well that were being created but as they were not linked to the acct I was thinking the trigger is not working.Thanks again