[SalesForce] Displaying an error message on a visualforce page

So I'm trying to display an error message on a visualforce page using

ApexPages.addMessage

or

ApexPages.addMessages

As suggested in numerous threads and posts like this one: https://www.interactiveties.com/blog/2015/visualforce-apex-pagemessages.php

On my visualforce page I have

<apex:pageBlock>
    <apex:pageMessages></apex:pageMessages>
</apex:pageBlock>

but nothing is actually popping up there.

In my controller class I add a message like this:

public PageReference exchangeInv() {
  if (opp.StageName == 'Contract Executed') {

    // do some stuff

    PageReference pageRef = new PageReference('/'+opp.Id);
    return pageRef;
  }
  else {
    ApexPages.addMessages(new applicationException('error'));
    return null;
  }
}

It will get into that else case where I expect it to, and that error message will show up in the log, but will not show up inside

<apex:pageMessages>

Can anyone see where I'm going wrong here?

Best Answer

You need to rerender pageMessages section by commandButton's attribute

<apex:pageBlock>
    <apex:pageMessages id="msgId"/>


    <apex:commandButton name="Submit" action="{!exchangeInv}" rerender ="msgId"/>
</apex:pageBlock>

Take this approach:

Since you are throwing applicationException, so better to use throw new applicationException and in the catch block, wrap that message into pageMessages

public PageReference exchangeInv() 
{
    try
    {
        if (opp.StageName == 'Contract Executed') {
        // do some stuff
        PageReference pageRef = new PageReference('/'+opp.Id);
        return pageRef;
      }
      else {
        throw new applicationException('error');
        return null;
      }
    }catch (Exception ex)
    {
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
        ApexPages.addMessage(msg);
        return null;
    }  
}

or, if you don't want to use applicationException then use the error into pageMessages as follows:

public PageReference exchangeInv() 
{

    if (opp.StageName == 'Contract Executed') {
        // do some stuff
        PageReference pageRef = new PageReference('/'+opp.Id);
        return pageRef;
      }
      else {
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'error');
        ApexPages.addMessage(msg);
        return null;
      }

}
Related Topic