0
votes

I have custom validation rules defined on my custom employee__c object in salesforce. I use a standard controller visualforce page with custom extension to show a UI to the user for data entry. My challenge is to show the validation rule error to the user in an easy to read manner. Here is the part of the code that I have.

Visualforce

<apex:page standardController="Employee__c" extensions="EmployeeExtension" sidebar="false">
 <apex:sectionHeader ...
 <apex:form id=fr>
   <apex:pageMessages id="errMsg"/>
    <apex:pageBlock title="Employee Edit" mode="edit" >
    <apex:pageBlockButtons >
    <apex:commandButton action="{!mySave}" value="Save" reRender="errMsg"/>
    <apex:commandButton action="{!cancel}" value="Cancel"/>
    ....
 </apex:form>
</apex:page>

Apex Controller

public class EmployeeExtension {
 ....
 public PageReference mySave(){
  ....
  try{
    upsert empList;
  } catch (DMLException ex) {
     ApexPages.addMessages(ex);
  }
 }
}

This shows the errors at the page top which is the way I want, but it shows twice. Here is how it will display the error at page top.

  • error_message_from_custom_validation_comes_here
  • TriggerEmployee: Exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, error_message_from_custom_validation_comes_here

In my entire controller I do not have any other DML operations nor do I use ApexPages.addmessage any where else. The strange thing is if I remove

ApexPages.addMessages(ex);

while keeping the try catch block as is, then I see only

  • error_message_from_custom_validation_comes_here

I wonder why it shows the page messages in vf page even when I am not sending anything from controller. I appreciate all your responses, but I would like to see solutions not involving javascript or jquery.

1

1 Answers

1
votes

You can use this:

ApexPages.addMessage(
    new ApexPages.Message(
      ApexPages.severity.ERROR,
      ex.getMessage()
    )
  );

Alternatively you could also imitate the standardController:

public class EmployeeExtension {
....
  public PageReference mySave(){
    /* do your thing */
    return this.standardController.save();
  }
}

This way you return the page reference of the save which is the standard behaviour (if you want to imitate this) and if there is a validation error it will show up in the tag and only the nice formatted message will show up.

You don't need a reRender on the save:

<apex:page standardController="Employee__c" extensions="EmployeeExtension" sidebar="false">
  <apex:sectionHeader ...
  <apex:form id=fr>
    <apex:pageMessages/>
    <apex:pageBlock title="Employee Edit" mode="edit" >
      <apex:pageBlockButtons >
        <apex:commandButton action="{!mySave}" value="Save"/>
        <apex:commandButton action="{!cancel}" value="Cancel"/>
    ....
  </apex:form>
</apex:page>

Salesforce/Visualforce will do the rest for you :)