[SalesForce] Throwing errors on a standard page layout using Apex!

Scenario: I have a custom button on a standard layout, which will call an apex class to do some validation on a record. If not validated, it needs to throw out some errors on that page. What are the best UX options to achieve this?

I am not too sure how to achieve this. Within a trigger, you can use the addError method to add the custom errors.

Can my Apex class reference the fields of a standard object? The ideal approach would be to do the following:

Contact.Email.addError('Please enter the right format here');

How can I achieve this via an apex class that the custom button will call?

What I have thought: Having a VF Page popup on the screen so that user can see all the errors, but that's not the best approach as UX is a big deal for this application


Best Answer

You could exercise your validation logic in apex using either a Visualforce page or webservice called from Javascript. There is a good webservice example here:

Best practice for calling Apex methods from custom button?

Using Visualforce you have methods for error message handling built in. The most popular post here on StackExchange outlines when to use the various Visualforce message options.

Difference between the multiple messaging options in Visualforce?

The short answer is that you need an outputPanel VF component in your page that renders if you have a message to show. Example, with Twitter bootstrap markup/styles:

<apex:outputPanel rendered="{!hasMessages}" >
  <div class="row">
      <div class="span12">
          <div class="alert alert-error failureMsg">
              <strong><apex:messages styleClass="unstyled" /></strong>

And your apex class has something like this:

//error handling properties to be aware of and display messages on error to the user on the page
public Boolean hasMessages { get { return ApexPages.hasMessages(); }}

I think your best bet is to just include the detail of the record page on the VF "error page" so adding the apex:detail component just below your error text would make the page look just like the standard object layout but it would in fact be a VF page with your validation logic and error surfacing.