How to add error message in Visualforce page?

Sample Code:

Visualforce page:

<apex:page controller="Sample" sidebar="false" >
<apex:pagemessages />
<apex:form >
    <apex:pageblock >     
        <apex:pageBlocksection >
            <apex:pageblockSectionItem >Name:</apex:pageblockSectionItem>
            <apex:pageblockSectionItem ><apex:inputtext value="{!nam}" /></apex:pageblockSectionItem>         
            <apex:pageblockSectionItem >Age:</apex:pageblockSectionItem>         
            <apex:pageblockSectionItem ><apex:inputtext value="{!age}" /></apex:pageblockSectionItem>         
        </apex:pageBlocksection>       
        <apex:pageblockButtons >
            <apex:commandButton value="Submit" action="{!submit}" reRender=""/>
        </apex:pageblockButtons>
    </apex:pageblock>
</apex:form>
</apex:page>


Apex Controller:

public class Sample
{
    public String nam {get;set;}
    public Decimal age {get;set;}

    public void submit()
    {
        try
        {
            Member__c m = new Member__c();
            m.Name = nam;
            m.Age__c = age;
            insert m;
        }
        catch(Exception e)
        {
            String error = e.getMessage();
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,error));
        }
    }

}


Output:



Cheers!!!

No comments:

Post a Comment