Only in batch class finish method, We can call another batch class. If you will call another batch class from batch class execute and start method, then Salesforce will throw below runtime error.
System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.
Here in below example there are two batch classes “Batch1” and “Batch2“.
I want to execute “Batch2” after finish the “Batch1“.
So, I’m calling “Batch2” class in “Batch1” finish method.
Batch1:
global class Batch1 implements Database.Batchable<Sobject>{
//Method to get the data to be proceesed
global database.Querylocator Start(Database.BatchableContext bc){
String query = 'Select Id, Name From Account Limit 1000';
return Database.getQueryLocator(query);
}
//Method to execute the batch
global void execute(Database.BatchableContext bc, Sobject[] scope){
for(Sobject s : scope){
Account a = (Account)s;
// TO DO
// add your logic
}
}
//Method to be called after the excute
global void finish(Database.BatchableContext bc){
//Add your start code for the other batch job here
Database.executeBatch(new Batch2());
}
}
Batch2:
global class Batch2 implements Database.Batchable<Sobject>{
//Method to get the data to be proceesed
global database.Querylocator start(Database.BatchableContext bc){
string query = 'Select Id, Name From Contact Limit 1000';
return Database.getQueryLocator(query);
}
//Method to execute the batch
global void execute(Database.BatchableContext bc, Sobject[] scope){
for(Sobject s : scope){
Contact c = (Contact)s;
// TO DO
// add your logic
}
}
//Method to be called after the excute
global void finish(Database.BatchableContext bc){
}
}
Here I’ve a custom “Student__c” object. There is a validation rule on “Date_of_Birth__c” field, that Date of Birth cannot be greater than today. And I’m using a visualforce page to insert the data in “Student__c” object. So, I need to show the validation rule error message in visualforce page.
Validation Rule:
Below is my controller which gave the solution for displaying validation error message on visualforce page.
Controller:
public with sharing class StudentExt {
public Student__c student{get;set;}
public StudentExt(ApexPages.StandardController controller) {
student = (Student__c)controller.getRecord();
}
public Pagereference saveStudent() {
try {
Upsert student;
return new Pagereference('/' + student.Id);
}
catch(DMLException de) {
Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, de.getDmlMessage(0)));
return NULL;
}
catch(Exception e) {
Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, e.getMessage()));
return NULL;
}
}
}