Skip to main content
Sara Monksfield (RSC) ha preguntado en #Apex
Hi, I'm trying to learn so decided to write a trigger that pre-populated the SLA field when an account was created, and also created an opportunity with pre-populated fields.

I have managed to either:

Create an account WITHOUT the pre-populated SLA field and WITH an associated opportunity,

OR

Create an account WITH the pre-populated SLA field and create an opportunity that is NOT associated with the account.

I can't work out how to combine the two, can anyone help please?

This is my code:

This version creates both correctly, but excludes the auto completion of the SLA field (used After insert as Before causes read only error):

trigger NewAccountOppTEST on Account (After insert) {

    List<Opportunity> OppList = new List<Opportunity>();

    

    //Auto populate SLA field for new account

    for (account acc : Trigger.new ){ 

                   

{

    //Create opportunity

    Opportunity opp = new Opportunity();

    opp.name        = 'Auto Created again';

    opp.CloseDate   = Date.today()+7;

    opp.Stagename   = 'Prospecting';

    opp.AccountID   = acc.id;  

    OppList.add(opp);

Insert OppList;

}

}

This version creates everything but the opportunity is orphaned:

trigger NewAccountOppTEST on Account (Before insert, after update) {

    List<Opportunity> OppList = new List<Opportunity>();

    

    //Auto populate SLA field for new account

    for (account acc : Trigger.new ){ 

        acc.SLA__c  = 'Gold';            

{

    //Create opportunity

    Opportunity opp = new Opportunity();

    opp.name        = 'Auto Created again';

    opp.CloseDate   = Date.today()+7;

    opp.Stagename   = 'Prospecting';

    opp.AccountID   = acc.id;  

    OppList.add(opp);

Insert OppList;

}

}
4 respuestas
  1. 10 jun 2021, 15:43
    Hi Choccy, 

    I have written the same code in another way, hope this one works

    trigger NewAccountOppTEST on Account (After insert) {

        List<Opportunity> OppList = new List<Opportunity>();

    List<Account> accList = [select Id, SLA__c from Account where Id IN:Trigger.new];

        

        //Auto populate SLA field for new account and create related opportunity

        for (account acc : accList ){ 

                       acc.SLA__c  = 'Gold';

        Opportunity opp = new Opportunity();

        opp.name        = 'Auto Created again';

        opp.CloseDate   = Date.today()+7;

        opp.Stagename   = 'Prospecting';

        opp.AccountID   = acc.id;  

        OppList.add(opp);

    update accList;

    if(OppList.size() >0) {

    Insert OppList;

    }

    }

    Thanks 

    Surya G
0/9000