Now and then every developer must have thought about adding messages to the Visualforce page that they have created. When there is some error in execution of the function or when there is problem in the DML operation, page messages can help us and save a lot of our debugging time. This is what we will discuss, how to add pagemessages on visualforce pages from APEX code.
APEX Code
First thing first, we will create a class which will add the page message to the page.
public class PageMsg { public string str { get; set;} public void addPgMsg(){ apexpages.addMessage(new ApexPages.message(Apexpages.Severity.INFO,str)); } }
In this class we have used the method addMessage to add an object of type pagemessage to the visualforce page. This method as we can see takes an argument of message class object. The constructor require two arguments, first is the severity of the message. Whether it will be a confirm message, an error message, or a warning message, or just an info message. Second parameter is the string which will be shown in the message. For this example we will show a string after taking input from the user.
Visualforce Page
<apex:page controller="pagemsg"> <apex:form> <apex:pageMessages id="pbm"/> <apex:inputText value="{!str}"/> <apex:commandButton action="{!addPgMsg}" value="Add string Message"/> </apex:form> </apex:page>
Here we have simply added input field to get the string and then showing it in the page message.
Support
That’s all about adding page message to visualforce page from apex, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views on how to make this code better, in comments section below.