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

URGENT: Help to display error message in VF Page if no records are present in Execute Method

I have a VF page where a button is present.On click of it a batchjob runs and deletes the records from custom object.


So my design was I have controller 'batchctrl' for the VF Page which will call the execute method of the batch class.


Here is the execute method in my batchClass:

public     List<obj__c> objList= new List<obj__c>();

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

    for(sObject s:scope){
       obj__c x= (obj__c)s;       
    delete objList;


Finish Method:

global void finish (Database.BatchableContext BC){
    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email, ExtendedStatus
                          From AsyncApexJob where Id =:BC.getJobId()];

     ObjRecordsSize = objList.size();
       batchctrl b= new batchctrl();


In the finish method i'm trying to call updateErrorMsg method of my batchctrl class to send the recordsize value and if it is zero i want to display an error message.


But i'm getting the below exception

System.FinalException: ApexPages.addMessage can only be called from a Visualforce page


So please let me know if they is any way I could display the error message in the VF Page.

I'm sure that there must be someway :)


Many thanks in advance :)




You can setup a JavaScript function that calls a method to check the number of batches processed after the batch is completed with an interval of 1 second.




Visualforce Page:

<apex:outputPanel id="OutputMessage">

    <script type="text/javascript">

        var done = {!done}; //Set the value of done with a boolean variable in controller denoting if batch is done processing




        function checkBatch(){


    <apex:pageMessages id="PageMessage" escape="false"/>


<apex:actionFunction action="{!checkBatchStatus}" name="myActionFunction" reRender="OutputMessage" />


Apex Controller:


public Id batchProcessId{get; set;}

public Boolean done{get; set;} //Don't forget to set to false on class constructor

public void executeBatch(){

    BatchClass delete = new BatchClass();

    batchProcessId = Database.executeBatch(delete);


public void checkBatchStatus(){

    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email, ExtendedStatus
                          From AsyncApexJob where Id =:batchProcessId];

        //Set done to true

        done = true; 

        if(a.TotalJobItems == 0){

            //Display your message...

            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'Message'));




  Hope ths helps!