show error message in visualforce page

Many times it is required to show warning,error or information messages on a visualforce page so as to indicate to the user. For these, salesforce provides page message,pagemessages,message and messages components.
We have to create a new instance of the message in apex and make sure we have placed the messages component on the visualforce page.
In the below example messages are displayed on button press if any of the input values are not submitted.
Visualforce Page
<apex:page extensions="ErrorDisplayDemoController" standardcontroller="Account">
 <apex:form>
   <apex:pageblock>
      <apex:pagemessages id="shwmsg"></apex:pagemessages>
         <apex:panelgrid columns="2">
           Account Name <apex:inputtext value="{!accountname}">
           Account Number <apex:inputtext value="{!accountnumber}">
           <apex:commandbutton action="{!UpdateAccount}" rerender="shwmsg" style="width: 70px;" value="Update">
         </apex:commandbutton></apex:inputtext></apex:inputtext></apex:panelgrid>
    </apex:pageblock>
 </apex:form>
</apex:page>
Controller
Public with sharing class ErrorDisplayDemoController { 
Public string accountname{get;set;} 
 Public string accountnumber{get;set;} 
 Public ErrorDisplayDemoController(ApexPages.StandardController controller) {
 } 

Public void UpdateAccount(){ 
     if(accountname == '' || accountname == null) 
         ApexPages.addmessage( new ApexPages.message(       ApexPages.severity.WARNING,'Please enter Account name')); if(accountnumber == '' || accountnumber == null) 
 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.error,'Please enter Account number')); 
 }
 }

1 comment:

  1. You r a STAR.
    Thank you so very much, i have also referred your SOSL example page. that worked like a charm. THank youu :)

    ReplyDelete