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
Alex DrewAlex Drew 

Create Opportunity after Custom Object Record type

I am new to APEX code to struggling with the process to try and create an Opportunity once a Custom Object record is created. So we have customer questionnaires (custom object) and the idea is that if that customer response to specific questions if met, to trigger an Opportunity on the Account. 
Is this possible or would I need to do something more sophisticated than a Trigger?
AndrewTaylorAndrewTaylor
You can do this via Apex; below is some sample code which assumes you have an Account__c lookup field to related Account.
 
trigger myCustomObjectTrigger on Custom_Object__c (after insert) {

    List<Opportunity> oppList = new List<Opportunity>();
    for(Custom_Object__c co : System.Trigger.new) {
        oppList.add(new Opportunity(Name = co.Name, AccountId = co.Account__c));  // add other fields to initialize, e.g. if there's a lookup back to this custom object record
    }
    insert oppList;

}

 
Alex DrewAlex Drew
Thanks for the reply. I think this is where it is getting complicated for me as the custom object doesn't have a lookup to the Account record. So essentially: Custom_Object_1__c > Custom_Object_2__c > Account.
Can the APEX deal with a multiple look up?
Thanks
AndrewTaylorAndrewTaylor
Yes, you'd need to query the parent of Custom Object 1 for the Account Ids though.  Something like:
 
trigger myCustomObjectTrigger on Custom_Object__c (after insert) {

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

   Set<Id> parentIds = new Set<Id>();

    for(Custom_Object__c co : System.Trigger.new) {
        parentIds.add(co.Custom_Object_2__c);
   }

   Map<Id, Custom_Object_2__c> parentMap = [select Id, Account__c from Custom_Object_2__c where Id IN :parentIds];

    for(Custom_Object__c co : System.Trigger.new) {
        oppList.add(new Opportunity(Name = co.Name, AccountId = parentMap.get(co.Custom_Object_2__c).Account__c));  // add other fields to initialize, e.g. if there's a lookup back to this custom object record
    }
    insert oppList;

}

 
Alex DrewAlex Drew
Hi, thanks for this and have got the trigger working. Thank you for the code. I now need to get the Opportunity to be created if a certain field in my Custom Object is of a specific value. So if 'co.name__C = test' for example. Would it be as simple as adding an IF statement to the creation of the opportunity?
AndrewTaylorAndrewTaylor
Yep, you can just add an IF block around the "oppList.add" line.