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
Sainath VenkatSainath Venkat 

trigger to create a record by catching the current created record id

On lead object, I have a trigger that will create two contacts, now I want to catch those two created Id's and create a record in Relationship__c object. On relationship object I have two fields Contact1__C and contact2__c, I want to pass two newly created contact id's after inserting in trigger to Contact1__c and Contact2__c fields in Relationship Object.

Can anyone help me out in this issue, my code is below.
trigger CreateContact on Lead (after insert) {
    List<Contact> conInsertList = new List<Contact>();
    List<npe4__Relationship__c> relation = new List<npe4__Relationship__c>();
    List<String> listEmail = new List<String>();
    for (Lead em : {
        if(em.Email != null){
    List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
    String cemail;
    for(Contact ce : cem){
        cemail = ce.Email;
    for(Lead ld : {
        if (ld.Email != cemail && ld.Parent_Fill__c == false) {
            Contact cnt = new Contact();
            cnt.FirstName = ld.FirstName;
            cnt.LastName = ld.LastName;
            cnt.Email = ld.Email;
            if(ld.Email != cemail && ld.Parent_Fill__c == true ){
                Contact cnt1 = new Contact();
                cnt1.FirstName = ld.Parent_First_Name__c;
                cnt1.LastName = ld.Parent_Last_Name__c;
                cnt1.Email = ld.Parent_Email__c;
                Contact cnt2 = new Contact();
                cnt2.FirstName = ld.FirstName;
                cnt2.LastName = ld.LastName;
                cnt2.Email = ld.Email;
        INSERT conInsertList;
        List<Id> conInsert = new List<Id>();
        for(Contact con : conInsertList){

Prangya JenaPrangya Jena
Hi Sainath,

As it is a good practise to have one trigger per object. In your scenario you have to perform insertion to Relationship object based on Contact object. It will be better if you write your logic in apex class and call it from the trigger.

Please let me know if you need help.