+ Start a Discussion
SaiVineeth MaddulaSaiVineeth Maddula 

Add Contacts to Campaign using Batch Class

Hi,
I have  a requirement where I would like to add contacts to campaign record when status(Custom Field) of Contact is Closed Lost. I was stuck at adding contacts to campaign. Can someone help me acheive this since I am new to salesforce..

//Batch Class

global class AddContactsToCampaignBatch implements Database.Batchable<SObject>{
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id, Name 
                                         FROM Campaign 
                                         WHERE Name = 'Pipeline Campaign']);
    }
    global void execute(Database.BatchableContext BC, List<Contact> conList) {
        for(Contact con : [SELECT Id, Status__c 
                           FROM Contact]) {
                               if(con.Status__c == 'Closed Lost') {
                                  conList.add(con); 
                               }
                           }
        update conList;
    }
    global void finish(Database.BatchableContext BC) {
        
    }
}

Thanks in Advane....
Raza0195Raza0195
Basically, You want to create contact related to Campaign while batch executing.so there we need to create relationship between them(contact or Campaign Objects) Right ?. Please do let me know if i am correct.
SaiVineeth MaddulaSaiVineeth Maddula
No, Actually I want to add contacts as Campaign Members when the status of Contact is 'Closed Lost'. Help me doing this...
Maharajan CMaharajan C
Hi Sai,

Please refer the below code: 
 
global class AddContactsToCampaignBatch implements Database.Batchable<SObject>{
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id, Status__c 
										 FROM Contact 
                                         WHERE Status__c = 'Closed Lost']);
    }
    global void execute(Database.BatchableContext BC, List<Contact> conList) {
	
	try
	{
		Campaign camp = [SELECT Id, Name FROM Campaign WHERE Name = 'Pipeline Campaign' limit 1];
		List<CampaignMember> cmList = new List<CampaignMember>();
        for(Contact con : conList) 
		{
			CampaignMember cm = new CampaignMember(CampaignId = camp.Id,
                      ContactId = con.Id, Status = 'Sent');
			cmList.add(cm);
        }
		if(!cmList.isEmpty())
        insert cmList;
    }
	}
	catch(Exception ex)
	{
		system.debug(' Exception ==>' + ex.getMessage());
	}
    global void finish(Database.BatchableContext BC) {
        
    }
}

Thanks,
Maharajan.C​​​​​​​