[SalesForce] Rerendering apex:pageMessages (when clicking button) causes the message to be not displayed

I had an issue when re-rendering apex:pageMessages when a command button is clicked. If I remove the re-render from the apex:commandButton, the apex:messages is displayed correctly.

Here's my visualforce page :

<apex:page standardController="Case" extensions="RerenderPageMessages">
<apex:form >        
    <apex:outputPanel id="myPanel">
        <apex:pageMessages id="errorMessage" />
    </apex:outputPanel>

    <apex:pageBlock >            
        <apex:pageBlockButtons location="bottom">
            <apex:commandButton id="myButton" value="Save" action="{!AddErrorMessage}" rerender="myPanel"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>

</apex:form>

and here's my controller :

public class RerenderPageMessages {

public RerenderPageMessages(ApexPages.StandardController stdController) {
}

public PageReference addErrorMessage() {
    ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error Message!'));        
    return ApexPages.currentPage();
}

}

Best Answer

Return null in your addErrorMessage method instead. This will cause a rerender instead of a redirect.

public PageReference addErrorMessage() {
    ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error Message!'));        
    return null;
}