Clear Apex:PageMessages without losing viewstate

There are some alternative ways to display error messages, but like @Mark Pond answered you cannot clear the ApexPages.getMessages(). Also, you cannot iterate over it and replace the elements on it, or rather you can but it doesn't stick just like you observed with the clear() call.

I suspect that the List that is returned by getMessages() is defensive copy of what is actually stored.

There are alternatives, such as doing away completely with apex:pageMessages in favor of using apex:pageMessage and building up your own error message(s) to display under that tag. Obviously there are drawbacks such as maintainability with having to manually handle and report on all of the errors.


You won't need to clear any existing messages (in fact you can't modify or clear the collection), nor will you lose your viewstate. What you are describing is exactly how the system works.

Each time the page is posted, the pagemessages collection is cleared and any new errors are added and displayed for the new request/response cycle.

Sample Working Controller:

public with sharing class PageController {

    public string myStringValue { get; set; }       
    public PageController() {}

    public PageReference action1() {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Info Message'));
        return null;
    }
    public PageReference action2() {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error Message'));
        return null;
    }
}

and the page

<apex:page controller="PageController" >
    <apex:form >
        <apex:pageMessages id="messages" /> 
        <apex:inputText value="{!myStringValue}" />
        <apex:commandButton action="{!action1}" value="action 1" rerender="messages" />
        <apex:commandButton action="{!action2}" value="action 2" rerender="messages" />
    </apex:form>
</apex:page>

If this doesn't describe your scenario or if you are seeing behavior that differs from this, can you provide more information and markup to support it?


As Peter Knolle mentioned, we can supress the error messsage that is being displayed.

I have done as follows and its working, its displaying custom message:

<apex:PageMessages rendered="{!showErrorMessages}"/>

<apex:pageMessage strength="1" severity="error" summary="Error Message2" rendered="{!NOT(showErrorMessages)}"/>

controller:

 if(ApexPages.hasMessages(ApexPages.Severity.Error))
 {

  List<ApexPages.Message> listOfMessage=ApexPages.getMessages();

   for(integer i=0;i<listOfMessage.size();i++)

   {

   if(listOfMessage.get(i).getSummary().contains('Message 1'))

   {

      showErrorMessages=False;

   }
  }
}