Sunday, November 18, 2018

Apex Trigger For Creating a Related Record on Account Object

Trigger On Account Object To Create a Related Record 

Hi Friends. . . 😄😄😄
Hope you are all doing well.
Today I'm going to discuss on How to Create a Related record on any Object (Standard / Custom) In Salesforce.

Suppose, we are creating a New Account & We need to have a related records like Contact, Opportunity . . . 
For this kind of Situations, we will use APEX Trigger that will solve all the Business use cases.
Here we are going to create a Trigger for creating the Related records on Account Object.

USE CASE : Trigger For Creating the Related Record ( Opportunity Record ) When ever New Account is Created or If an Account is Already created but NO OPPORTUNITIES are created for that Account then will create a Related Opportunity for that Account (Existing Accounts).

 /*  
 Description : Create New Opportunity on Account (Related Record) when no Opportunity was created before to that Account.  
 This Trigger Even Used for Creating an Opportunity When ever New Account was created.  
 */  
 trigger AddRelatedRecord on Account(after insert, after update)   
 {  
   //Create Opportunity List To Store the Opportunities   
   List<Opportunity> opportunityList = new List<Opportunity>();  
   //Get Related Opportunity Records For The Accounts  
   Map<Id,Account> accountsWithOpp = new Map<Id,Account>  
   ([SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);  
   // Check for All the Accounts & If Any Accounts doesn't have the Opportunity   
   Then ADD The Related Opportunity to that account.  
   // Iterate Through Each Account.  
   for(Account acc : Trigger.New) {  
     System.debug('accountsWithOpp.get(acc.Id).Opportunities.size()=' + accountsWithOpp.get(acc.Id).Opportunities.size());  
     // Check if the account already has a related opportunity.  
     if (accountsWithOpp.get(acc.Id).Opportunities.size() == 0) {  
       // If it doesn't have then, add Default opportunity  
       opportunityList.add(new Opportunity(Name=acc.Name + ' Opportunity',  
                     StageName='Prospecting',  
                     CloseDate=System.today().addMonths(2),  
                     AccountId=acc.Id));  
     }        
   }  
   if (opportunityList.size() > 0) {  
     insert opportunityList;  
   }  
 }  


EmoticonEmoticon