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
dinesh Devaraj 6dinesh Devaraj 6 

when i want to create contacts after account stage changes from hot to warm using batch ape how can i do it?

Adilson Arcoverde JrAdilson Arcoverde Jr
Hi Dinesh,

I think the best approach is to create a trigger on Account, because you would be able to check Trigger.new values against Trigger.oldValue and then you can call a batch. Try the following code:

AccountTrigger.trigger
trigger AccountTrigger on Account( after update ) {
    if( Trigger.isAfter && Trigger.isUpdate ) {
        List<Account> accountsToProcess = new List<Account>();
        for( Account acc : Trigger.new ) {

            if( acc.Stage__c == 'Hot' && Trigger.oldMap( acc.Id ).Stage__c == 'Warm' ) {
                accountsToProcess.add( acc );        
            }
        }

        if( accountsToProcess.size() > 0 ) {
            Database.executeBatch( new NewContactsBach( accountsToProcess ) );
        }
    }
}


NewContactsBach.cls
global class NewContactBatch implements Database.Batchable<sObject> {
	
	String query;
    private List<Account> accountsToProcess;
	
	global NewContactBatch(List<Account> accountsToProcess) {
        this.accountsToProcess = accountsToProcess;
	}

	
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		query = 'Select Id, Stage__c, Name from Account where Id in :accountsToProcess';
		return Database.getQueryLocator(query);
	}

   	global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<Account> accs = (List<Account>) scope;

        List<Contact> contactsToInsert = new List<Contact>();
        for( Account acc : accs ) {
            Contact newContact = new Contact();
            newContact.AccountId = acc.Id;
            // Add aditional fields here
            contactsToInsert.add( newContact );
        }

        if( contactsToInsert.size() > 0 ) insert contactsToInsert;
	}
	
	global void finish(Database.BatchableContext BC) {
		
	}
	
}

I hope you find this solution useful. If it does please mark as Best Answer to help others too.

Regards.