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
Teja KTeja K 

Need help with below trigger scenario

Hello All, 

Need some help with the below scenario.

I have a 2 custom objects. Will be loading the data on parent object and based on the email field only unique email Id records should be created on the child object.

Example data: 
below is the data to load on the parent object
Name               Email
A                       A@gmail.com
A                       A@gmail.com
B                       B@gmail.com

Expected Output on child object:  
Name               Email
A                       A@gmail.com
B                       B@gmail.com
Abdul KhatriAbdul Khatri
Hi Teja,

Please find the below code. Please note as per you requirement this code will work when you insert the parent object

Trigger
trigger ParentObjectTrigger on Parent_Object__c (after insert) {

    Map<String, Parent_Object__c> emailMap = new Map<String, Parent_Object__c>();
    for(Parent_Object__c po : trigger.new){
        if(!string.isBlank(po.Email__c) && !emailMap.containsKey(po.Email__c))
            emailMap.put(po.Email__c, po);
    }
    
    if(emailMap.isEmpty()) return;
    
    Set<String> emailSet = new Set<String>();
    for(Child_Object__c co : [SELECT Id, email__c FROM Child_Object__c WHERE email__c = :emailMap.keyset()]){       
       emailSet.add(co.Email__c);         
    }    
    
    List<Child_Object__c> coListToInsert = new List<Child_Object__c>();
    for(String strEmail : emailMap.keyset()){
        if(!emailSet.contains(strEmail)){
            Child_Object__c coToInsert = new Child_Object__c();
            coToInsert.Name = emailMap.get(strEmail).Name;
            coToInsert.Parent_Object__c = emailMap.get(strEmail).Id;
            coToInsert.Email__c = strEmail;
            coListToInsert.add(coToInsert);
            
        }
    }
    
    Database.insert(coListToInsert);
}

Test Class
@isTest
public class ParentObjectTrigger_Test {

    @isTest
    public static void test_parentchildEmail(){
               
        List<Parent_Object__c> poList = new List<Parent_Object__c>{
            new Parent_Object__c (Name = 'A', Email__c = 'A@gmail.com'),
            new Parent_Object__c (Name = 'A', Email__c = 'A@gmail.com')
        };
        
        Test.startTest();
        insert poList;
        Test.stopTest();
        
        List<Child_Object__c> coList = [SELECT Id FROM Child_Object__c WHERE Email__c = 'A@gmail.com'];
        system.assert.isTrue(coList.size()==1);
        
        
    }
}

I hope this will help.

Please do not forget to mark it a best answer