Salesforce | How to show different apex message at different places on clicking a single button?

|
| By Webner

In a Visualforce page we have multiple UI blocks (for simplicity we have considered only 2 blocks below). In each block we have a form with some html elements and few action buttons to submit form of only that block. In addition we also have global action buttons which submit each form under every block. When we click block specific action button and form encounters an error (like mandatory element error), we display the error above the block, like in the picture below:

Problem occurred when we were clicking global Save and Close button. In this case if each block form had an error, it was showing all the error messages above each block as shown in image below:

To solve this, we used component apex:pagemessage which is also used to show a single message. This is the logic we used to solve it:

1. Take two string class variables and assign error message to them.

For Example:

String primarymsg=”Error in primary component
String contingentmsg=”Error in contingent component”;

2. Now take two boolean values.

Boolean pcheck, check;

Initially set them as false. This will hide your apex:messages.

In apex class, the method which will be called on clicking the global button will set the values to true (you can apply logic to make only required variables true, here we are conveying the idea):

public PageReference saveAndClose()
{
pcheck=true; //means show this message
ccheck=true; //means show this message as well
return null;
}

3. Use apex:pageMessage in both the blocks. Both the blocks are enclosed in a single page block:

<apex:pageblock id="account" title="Beneficiary Details" >
<apex:pageblock id="primaryaccount" title="Primary Beneficiary Details">
<apex:pageMessage summary="{!primarymsg}" severity="error" strength="3" rendered="{!pcheck}" />
</apex:pageblock>
<apex:pageblock id="contingentaccount" title="Contingent Beneficiary Details">
<apex:pageMessage summary="{!cmsg}" severity="error" strength="3" rendered="{!ccheck}" />
</apex:pageblock>
</apex:pageblock>

4. Now call the method on button click:

<apex:commandButton action="{!saveAndClose}" rerender="account" value="Save and Close" id="close" />

This will give the result as:

Leave a Reply

Your email address will not be published. Required fields are marked *