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
Mayur ShindeMayur Shinde 

Hi team pls help me how to write this trigger.

Pls help me....
Use case
-On Opportunity object
-  Create Fields FirstName,LastName,Email,Phone.
-  Create checkbox 'create account & contact'.
-create contact lookup on opportunity.
-  When opportunity record is saved, and the checkbox is set as true. Insert new Account & Contact and connect this opportunity with that Account & Contact.
- Only trigger event to take care of is Insert.

Trigger on opportutnity
pls any one help me n how to write in best practice....
Best Answer chosen by Mayur Shinde
mritzimritzi
Hi Mayur,

you will have to create custom fields in Opportunity Object as mentioned
(Create Fields FirstName,LastName,Email,Phone,
Create checkbox 'create account & contact',
create contact lookup on opportunity,)

Once that is done:
You have to write a trigger on Opportunity Object and create an Apex Class to handle the logic

Trigger:
 
Trigger OpportunityTrigger on Opportunity(after Insert){
    if(Trigger.isAfter && Trigger.isInsert){
        OpportunityTriggerHandler.createAccountContact(Trigger.new);
    }

}
Apex Class:
public with sharing class OpportunityTriggerHandler{
    public static void createAccountContact(List<Opportunity> opportunityList){
        List<Account> accountList = new List<Account>();
        List<Contact> contactList = new List<Contact>();
        List<Opportunity> oppUpdateList = new List<Opportunity>();
        Map<Id,Account> oppAccountMap = new Map<Id,Account>();
        Map<Id,Contact> oppContactMap = new Map<Id,Contact>();
        // please correct field API names, copy more field values from opportuntiy to Account/contact
        // make changes whereever required to suit your needs
        for(Opportunity opp : opportunityList){
            // if checkbox is true
            if(opp.Create_Account_Contact__c == TRUE){
                Account account = new Account();
                account.Name = opp.First_Name__c + ' ' + opp.Last_Name__c;
                //copy other required fields as well
                accountList.add(account);
                oppAccountMap.put(opp.Id,account);

                Contact contact = new Contact();
                contact.LastName = opp.last_Name__c;
                contact.Phone = opp.Phone;
                contactList.add(contact);
                oppContactMap.put(opp.Id,contact);
            }

        }
        try{
            insert accountList;
            insert contactList;
            for(Opportunity opp: opportunityList){
                Opportunity o = new Opportunity();
                o.Id = opp.Id;
                o.AccountId = oppAccountMap.get(opp.id).Id;
                o.Contact__c = oppContactMap.get(opp.Id).Id;
                oppUpdateList.add(o);
            }
            update oppUpdateList;
        }catch(Exception ex){
            System.debug(ex);
        }

    }
}

Please mark this as Best Answer, if this solves your problem.

 

All Answers

Kai Herng LauKai Herng Lau
Hi Mayur,

How can I get the FirstName, LastName, Email and Phone from Opportunity records?
Second question is the contact lookup you mention above, is this a custom field?
 
mritzimritzi
Hi Mayur,

you will have to create custom fields in Opportunity Object as mentioned
(Create Fields FirstName,LastName,Email,Phone,
Create checkbox 'create account & contact',
create contact lookup on opportunity,)

Once that is done:
You have to write a trigger on Opportunity Object and create an Apex Class to handle the logic

Trigger:
 
Trigger OpportunityTrigger on Opportunity(after Insert){
    if(Trigger.isAfter && Trigger.isInsert){
        OpportunityTriggerHandler.createAccountContact(Trigger.new);
    }

}
Apex Class:
public with sharing class OpportunityTriggerHandler{
    public static void createAccountContact(List<Opportunity> opportunityList){
        List<Account> accountList = new List<Account>();
        List<Contact> contactList = new List<Contact>();
        List<Opportunity> oppUpdateList = new List<Opportunity>();
        Map<Id,Account> oppAccountMap = new Map<Id,Account>();
        Map<Id,Contact> oppContactMap = new Map<Id,Contact>();
        // please correct field API names, copy more field values from opportuntiy to Account/contact
        // make changes whereever required to suit your needs
        for(Opportunity opp : opportunityList){
            // if checkbox is true
            if(opp.Create_Account_Contact__c == TRUE){
                Account account = new Account();
                account.Name = opp.First_Name__c + ' ' + opp.Last_Name__c;
                //copy other required fields as well
                accountList.add(account);
                oppAccountMap.put(opp.Id,account);

                Contact contact = new Contact();
                contact.LastName = opp.last_Name__c;
                contact.Phone = opp.Phone;
                contactList.add(contact);
                oppContactMap.put(opp.Id,contact);
            }

        }
        try{
            insert accountList;
            insert contactList;
            for(Opportunity opp: opportunityList){
                Opportunity o = new Opportunity();
                o.Id = opp.Id;
                o.AccountId = oppAccountMap.get(opp.id).Id;
                o.Contact__c = oppContactMap.get(opp.Id).Id;
                oppUpdateList.add(o);
            }
            update oppUpdateList;
        }catch(Exception ex){
            System.debug(ex);
        }

    }
}

Please mark this as Best Answer, if this solves your problem.

 
This was selected as the best answer
Ginny MahantGinny Mahant
trigger OpportunityAcctCtcSave on Opportunity__c (after insert) 
{
       List<Contact> conLst = new List<Contact>();
       List<Account> accLst = new List<Account>();
       List<Opportunity__c> opptyLst = new List<Opportunity__c>();
       List<Opportunity__c> opptyLstToUpd = new List<Opportunity__c>();
       Set<Id> opptyId = new Set<Id>();
       Set<Id> conId = new Set<Id>();
       Set<Id> accId = new Set<Id>();
    
       //CHECK THAT TRIGGER HAS FIRED AFTER INSERT
       if(trigger.isInsert && trigger.isAfter )
       {
                for(Opportunity__c  opp : Trigger.new)
             {
                //CHECK IF CREATE ACCOUNT & CONTACT CHECKBOX HAS BEEN CHECKED AND STORE THOSE OPPORTUNITY IDS
                //BUILD A LIST OF CONTACTS WITH EMAIL,FIRSTNAME,LASTNAME,PHONE FROM OPPORTUNITY
                if(opp.Create_Account_And_Contact__c)
                 {   
                    Contact objContact = New Contact();
                    objContact.FirstName = opp.First_Name__c;
                    objContact.LastName = opp.Last_Name__c;
                    objContact.Email = opp.Email__c;
                    objContact.Phone = opp.Phone_No__c;
                    objContact.Account = opp.Account__c;
                    conLst.add(objContact);
                    
                    Account objAccount = New Account();
                    objAccount.Name = opp.First_Name__c + '  '+ opp.Last_Name__c ;
                    accLst.add(objAccount);
                    opptyId.add(opp.Id); 
                }   
             }  
             try
             {
                 //INSERT CONTACT LIST AND RETRIEVE IDS OF ALL SUCCESSFULLY CREATED CONTACTS
                 if(conLst.size()>0)
                 {
                       Database.SaveResult[] srList = Database.insert(conLst,false); 
                       for (Database.SaveResult sr : srList) 
                       {
                            if (sr.isSuccess()) 
                            {
                                // Operation was successful, so get the ID of CONTACT CREATED
                                conId.add(sr.getId());
                            }
                            else 
                            {
                                // Operation failed, so get all errors                
                                for(Database.Error err : sr.getErrors()) 
                                {
                                    System.debug('The following error has occurred.');                    
                                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                                    System.debug('Contact fields that affected this error: ' + err.getFields());
                                }
                            }
                       }
                     Database.SaveResult[] srList = Database.insert(acctLst,false); 
                       for (Database.SaveResult sr : srList) 
                       {
                            if (sr.isSuccess()) 
                            {
                                // Operation was successful, so get the ID of CONTACT CREATED
                                accId.add(sr.getId());
                            }
                            else 
                            {
                                // Operation failed, so get all errors                
                                for(Database.Error err : sr.getErrors()) 
                                {
                                    System.debug('The following error has occurred.');                    
                                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                                    System.debug('Account fields that affected this error: ' + err.getFields());
                                }
                            }
                       }
                 }
                 conLst.clear();  
                 accLst.clear();
                 if(ConId.size() > 0)
                 {   
                     //QUERY ALL NEWLY CREATED CONTACTS
                     conLst = [SELECT Id, FirstName, LastName,Phone,Email, Account FROM Contact WHERE ID in :ConId];
                     //QUERY ALL NEWLY CREATED ACCOUNTS
                     accLst = [SELECT Id, FirstName, LastName,Phone,Email, Account FROM Contact WHERE ID in :ConId];
                     //QUERY THE OPPORTUNITY RECORDS HAVING CREATE ACCOUNT AND CONTACT CHECKBOX CHECKED
                     opptyLst = [SELECT Id, First_Name__c, Last_Name__c,Email__c,Phone_No__c,Account__c FROM Opportunity__c WHERE ID in :opptyId];
                     
                     //CHECK EACH CONTACT RECORD TO SEE IF IT MATCHES TO THE OPPORTUNITY AND PUT CONTACT 
                     //ID ON OPPORTUNITY 
                     for(Opportunity__c opptyRec : opptyLst)
                     {
                        for(Contact contactRec : conLst)
                        {
                            for(Account accRec : acctLst)
                            {
                                if(opptyRec.First_Name__c == conLst.FirstName &&
                                   opptyRec.Last_Name__c == conLst.LastName &&
                                   opptyRec.Email__c == conLst.Email &&
                                   opptyRec.Phone_No__c == conLst.Phone &&
                                   opptyRec.Account__c == conLst.Account &&
                                   accRec.Name == opptyRec.First_Name__c +'  '+opptyRec.Last_Name__c)
                                {   
                                    //SET CONTACT AND ACCOUNT LOOUP FIELD ON OPPORTUNITY WITH ID OF ITS CONTACT
                                    opptyRec.Contact__c =  contactRec.Id;
                                    opptyRec.Account__c = accRec.Id;
                                    opptyLstToUpd.add(opptyRec);
                                }   
                            }    
                        } 
                     }
                     //UPDATE THE LIST OF OPPORTUNITIES  
                     Database.SaveResult[] srList = Database.update(opptyLstToUpd,false);  
                     for (Database.SaveResult sr : srList) 
                       {
                            if (!sr.isSuccess()) 
                            {
                                 // Operation failed, so get all errors                
                                for(Database.Error err : sr.getErrors()) 
                                {
                                    System.debug('The following error has occurred.');                    
                                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                                    System.debug('Opportunity fields that affected this error: ' + err.getFields());
                                }
                            }
                 }
             }  catch(Exception e)
             {
                 System.debug('The following exception has occurred: ' + e.getMessage());
             }
       }
       
} //Please correct API Names as required
Ginny MahantGinny Mahant
Please create the custom fields and Contact Lookup field first then proceed to write the trigger