+ Start a Discussion
chirag.sapkota1.3947268332540498E12chirag.sapkota1.3947268332540498E12 

How to create error message in VF page while saving the form

Hello,
I have created a radio button yes/no on VF page. There is text box called "comment" on the page. I need a help on how to create an error message while saving the form(VF). If a user selects the option "Yes" he/she must put value on "comment box" or in another word coment box is not equal to Null. I am new to the VF page. If you could provide me the code, that would be great help. Thank you in advance.
sfdc18sfdc18
Hi Chirag,

 You can try something like this,

<apex:inputField value="{!Object__c.Comment__c}" required="{!IF(radiobutton =='Yes',true,false)}"/>

Regards,
Mayur
chirag.sapkota1.3947268332540498E12chirag.sapkota1.3947268332540498E12
Thank you Mayur,
Where should I add this logic? In the controller or VF page?
Developer.mikie.Apex.StudentDeveloper.mikie.Apex.Student
How is it going chirag, i actually came across this problem recently.

My problem was, whenever a validation rule was triggered I was re-directed to another page with a long bit of random writing that said the name of my rule, the field, etc. I always wanted the error message to appear on the page. To fix it, i added this tag to my visualforce page:

<apex:pageMessages />

and then to my visualforce controller, if you are using a custom save button you add code like this:

If your save button is:

Public PageReference saveDestinyTask(){
    


    if(System.currentPageReference().getParameters().get('clone') == '1'){

        //Set record id to null

        Tas.Id = null; 


    }


        upsert Tas;
        // Send the user to the detail page for the new account.
       PageReference pageRef= new PageReference('PageName');
        return pageRef;

    
    }

Then your new code will be:

Public PageReference saveDestinyTask(){
    


    if(System.currentPageReference().getParameters().get('clone') == '1'){

        //Set record id to null

        Tas.Id = null; 


]
  try {
        upsert Tas;
        // Send the user to the detail page for the new account.
       PageReference pageRef= new PageReference('PageName');

        return pageRef;

    } catch (Exception e) {    
     
             ApexPages.addMessages(e);        
        }
        return null;
    
basically, you add the try and insert yourt DML operation(example: upsert,insert) and page re-direction between its brackets and then add the catch line. So you are trying the operation, if there is an exception(validation etc) rather than re-directing, it will just display the error message.

Then you can simply add a valdiation rule.

Please mark as answers if correct.