[SalesForce] Error Message Display from Custom VisualForce Button without JavaScript

We are trying to remove all the custom buttons which was using Java Script code and replacing the same with VF buttons.(Migrating towards lightning)

However, i am not able to display the validation error message on my standard page layout(where the button is actually placed) which we are trying to validate on the apex controller class.

Example :

Controller Code

if(acc.phone == '' || acc.phone == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter Account phone'));

VisualForce Code

<apex:pageMessages id="showmsg"></apex:pageMessages>

Is there anyway we can display the validation error message from my controller code to the standard page layout or even custom VF page in some cases.

Thanks in advance and appreciate your help.

Venkatesh

Best Answer

Normally, I use to follow this approach. Create a CustomException class.

public class CustomException extends Exception {}

Controller

try
{
    if(acc.phone == '' || acc.phone == null)
    {
        throw new CustomException('Please enter Account phone');
    }
}
catch(Exception e)
{
    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
    ApexPages.addMessage(msg);
}

Now, error messages can be handled in the Exception block and displayed to the visualforce page inside <apex:pageMessages id="showmsg"></apex:pageMessages>