+ 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 : Trigger.new) {
        if(em.Email != null){
            listEmail.add(em.Email);
        }
    }
    
    List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
    String cemail;
    for(Contact ce : cem){
        cemail = ce.Email;
    }
    
    for(Lead ld : Trigger.new) {
        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;
            conInsertList.add(cnt);
        }
        else{
            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;
                conInsertList.add(cnt1);
                Contact cnt2 = new Contact();
                cnt2.FirstName = ld.FirstName;
                cnt2.LastName = ld.LastName;
                cnt2.Email = ld.Email;
                conInsertList.add(cnt2);
            }
        }
    }
    
    if(conInsertList.size()>0){
        INSERT conInsertList;
        List<Id> conInsert = new List<Id>();
        for(Contact con : conInsertList){
            conInsert.add(con.Id);
        }
    }
}

 
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.

Regards,
Prangya