function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jasonwanBellajasonwanBella 

Display custom error message from APEX without Visualforce

Is it possible to display custom error message from APEX without Visualforce?
 
Not sure if there is a simple method I might have overlooked. Trying to setup something similar to a validation rule where if a specific field has a value, I want to notify the user that something is wrong in my own custom wording.  Wondering if this works for APEX coding (say, on the top of the page).
ClaiborneClaiborne
Yes, there is a simple method. Implement a trigger that looks for your error condition. When the condition is found, it sets the error message to whatever you want. Then salesforce.com "fails" the operation and displays the error message. If no error condition is found, the operation simply proceeds.

Here is a sample:

Code:
// A slab cannot be deleted if it has shipped.
trigger BeforeDeleteSlab on Slab__c (before delete) {  
    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].Status__c == 'Shipped') {
                // Cannot delete a shipped slab
            Trigger.Old[i].addError('The slab cannot be deleted because it has been shipped.');
        }
        else if (Trigger.Old[i].Status__c == 'Unusable') {
                // Cannot delete a scrapped slab
            Trigger.Old[i].addError('The slab cannot be deleted because it has been scrapped.');  
        }
        else if (Trigger.Old[i].Status__c.contains('Converted')) {
                // Cannot delete a converted slab
            Trigger.Old[i].addError('The slab cannot be deleted because it has been converted to other product.');
        }                                  
    }
}

 

jasonwanBellajasonwanBella
ah yes. I knew there was a method call that would do the trick. Thanks.