Skip to main content
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....
4 answers
  1. Nov 24, 2017, 9:23 AM
    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.

     
0/9000