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
HTANIRSHTANIRS 

trigger on campaignmember to insert record in custom object.

Hi Friends,

I need help in writing trigger to insert a record in custom object.
I have enabled Person Account. Now I have Person Account and Account in my org. I have created a lookup field to Account in campaign.
My Requirement is :
When importing a campaignmember in a Campaign and mapping to Person Account. Then I should create a record in the custom object with the account name in campaign.
Custom Object is Related List to Person Account.

Am trying to solve using below Trigger but cannot able to create a new record in custom object.

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c from Campaign where Business_Accounts__c = :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Business_Accounts__c,cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Id);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}


Please Help.... Thanks in advance..
 
Best Answer chosen by HTANIRS
Steven NsubugaSteven Nsubuga
Here you go
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();
	
    Set<Id> personAccountIds = new Set<Id>();
	
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    } 
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
			personAccountIds.add(acc.Id);
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN :Trigger.newMap.keyset()];
	List<Customer_Profile__c> existingCustomerProfiles = [SELECT id, business_accounts__c, person_accounts__c FROM Customer_Profile__c WHERE person_accounts__c IN :personAccountIds];
	
	Set<String> bizAcctCombo = new Map<String>();
	for(Customer_Profile__c cp : existingCustomerProfiles) {
        bizAcctCombo.add(String.valueOf(cp.business_accounts__c) + String.valueOf(cp.person_accounts__c));
    }
	
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
				String bizAcctString = String.valueOf(cm.campaign.business_accounts__c) + String.valueOf(a.id);
				if (!bizAcctCombo.contains(bizAcctString)) {
					Customer_Profile__c cusObj = new Customer_Profile__c();
					cusObj.person_accounts__c = a.id;  
					cusObj.Business_accounts__c = cm.campaign.business_accounts__c ;
					customProfileList.add(cusObj);
					bizAcctCombo.add(bizAcctString);
				}
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}

 

All Answers

Steven NsubugaSteven Nsubuga
Give this a try
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c from Campaign where Id = :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Id, cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Business_Accounts__c);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}

 
HTANIRSHTANIRS
Hi Steven Nsubuga,

It is not working. Record is not getting inserted with the name. Can you please check and let me know.

Thanks.
Steven NsubugaSteven Nsubuga
Is the Business_Accounts__c field on Customer_Object__c a text field? Is it the field where the name of the Account should be stored?
If so then try this
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c, Business_Accounts__r.Name from Campaign where Id = :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Id, cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Business_Accounts__r.Name);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}

 
HTANIRSHTANIRS
Hi Steven Nsubuga,

It's a lookup field where need to populate the account selected.

My Requirement :
We have Account Lookup in Campaign. When Inserting record in campaignmember the account name from campaign should be populated in custom object with record created.

Thank.
 
Steven NsubugaSteven Nsubuga
So Business_Accounts__c  is a look up field to Account, and this look up exists on both Campaign and Customer_Object__c ?
HTANIRSHTANIRS
Hi Steven Nsubuga,
Yes. You are correct.

Thanks.
Steven NsubugaSteven Nsubuga
This should work
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c from Campaign where Id IN :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Id, cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Business_Accounts__c);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}
HTANIRSHTANIRS
Hi Steven Nsubuga,

I modified the code. Refer the below code. But I could not able to populate the values in Bold Line. Kindly check and how to insert that value.

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();
    
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    } 
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    
    for(CampaignMember cm : Trigger.new) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
                Customer_Profile__c cusObj = new Customer_Profile__c();
                cusObj.person_accounts__c = a.id;  
                cusObj.Business_accounts__c =cm.campaign.business_accounts__c ;
                customProfileList.add(cusObj);
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}


Thanks.
Steven NsubugaSteven Nsubuga
Here is the updated trigger. You cannot access campaign.business_accounts__c from trigger.new, you have to query it from Salesforce.
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();
    
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    } 
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN:Trigger.newMap.keyset()];
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
                Customer_Profile__c cusObj = new Customer_Profile__c();
                cusObj.person_accounts__c = a.id;  
                cusObj.Business_accounts__c =cm.campaign.business_accounts__c ;
                customProfileList.add(cusObj);
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}

 
HTANIRSHTANIRS
This works fine. Thanks.
Can you please tell me how to check Duplicate and insert the record.
HTANIRSHTANIRS
Hi Steven Nsubuga,

I want to check
1) the person account and the business account is same and already exists. If exists should not allow to insert. if not exists should allow to insert.
2) the person account exists but the business account is different then need to insert. Please suggest how to achieve this two conditions.

cusObj.person_accounts__c = a.id; 
cusObj.Business_accounts__c =cm.campaign.business_accounts__c ;


Thanks.

 
Steven NsubugaSteven Nsubuga
Try this
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();
    
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    } 
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN:Trigger.newMap.keyset()];
	Set<String> bizAcctCombo = new Map<String>();
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
				String bizAcctString = String.valueOf(cm.campaign.business_accounts__c) + String.valueOf(a.id);
				if (!bizAcctCombo.contains(bizAcctString)) {
					Customer_Profile__c cusObj = new Customer_Profile__c();
					cusObj.person_accounts__c = a.id;  
					cusObj.Business_accounts__c = cm.campaign.business_accounts__c ;
					customProfileList.add(cusObj);
					bizAcctCombo.add(bizAcctString);
				}
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}

 
HTANIRSHTANIRS
Hi Steven Nsubuga,

Got 1 issue and need your assistance.

I want to check if cusObj.person_accounts__c with same name already exists. If exists then I want to compare that field with cusObj.Business_accounts__c. If this both are getting inserted again I need to stop insert. If that is different then I can allow to insert.

Thanks.
Steven NsubugaSteven Nsubuga
Here you go
trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();
	
    Set<Id> personAccountIds = new Set<Id>();
	
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    } 
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
			personAccountIds.add(acc.Id);
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN :Trigger.newMap.keyset()];
	List<Customer_Profile__c> existingCustomerProfiles = [SELECT id, business_accounts__c, person_accounts__c FROM Customer_Profile__c WHERE person_accounts__c IN :personAccountIds];
	
	Set<String> bizAcctCombo = new Map<String>();
	for(Customer_Profile__c cp : existingCustomerProfiles) {
        bizAcctCombo.add(String.valueOf(cp.business_accounts__c) + String.valueOf(cp.person_accounts__c));
    }
	
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
				String bizAcctString = String.valueOf(cm.campaign.business_accounts__c) + String.valueOf(a.id);
				if (!bizAcctCombo.contains(bizAcctString)) {
					Customer_Profile__c cusObj = new Customer_Profile__c();
					cusObj.person_accounts__c = a.id;  
					cusObj.Business_accounts__c = cm.campaign.business_accounts__c ;
					customProfileList.add(cusObj);
					bizAcctCombo.add(bizAcctString);
				}
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}

 
This was selected as the best answer
HTANIRSHTANIRS
Hi Steven Nsubuga,

This is Working Fine.. Thanks for your help.