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
Abilash.SAbilash.S 

Trigger to create opportunity, if existing opportunity has 90% probability for that account.

Hi Everyone
I have wrote code to create opportunity, if existing opp has 90% probability. So I have used parent-child query to queru opportunities related accounts.
I have used FOR - IN - FOR loops. The records are creating in huge number. Please provide proper code with single for loop and use handler class. I came to know that should not use tripple for loops. Then how to achieve without multiple loops.


public static void createOpp(List<Account> accList) {
        
       List<Opportunity> oppList = new List<Opportunity>();
        Map<Id, Account> acctMap = new Map<Id, Account>([Select Id, (Select Id, probability from Opportunities) from Account WHERE ID IN :accList]);
 List<Account> acList = [Select Id, (Select Id, probability from Opportunities) from Account WHERE ID IN :accList];       
        for(Account a : accList) {
        
            for(Account ao: acList) {
            
                    for(Opportunity opp : ao.opportunities) {

                        if( opp.probability == 90){
                            Opportunity opptny = new Opportunity();
                            opptny.AccountId = a.Id;
                            opptny.Name      = a.Name + 'Opportunity with 90% prob new';
                            opptny.StageName = 'Prospecting';
                            opptny.probability = 90;
                            opptny.CloseDate = System.today().addMonths(3);
                            oppList.add(opptny);
                        }
                   }
               }
            }
        
        try{
        if(oppList.size() > 0){
            insert oppList;
            }
        } catch (DmlException e) {
            system.debug('Exception caused-->'+e.getMessage());
       } 
   }
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhilash,

Is this trigger on Account or Opportunity? Can you paste the trigger code as well and also as per your question you mentioned  that if existing opportunity has probability  as 90% then how does trigger on Account come here.

Can you clarify more on this s I can share the proper code for the same.

Thanks,.