2

I have a visualforce page with a controller extention. This page has some inputfields where

I want to send a waring on the page before insert if the fielsd are filled in incorrectly.

I am using a trigger but this redirects my to the standar errorpage of SF.

How can I addmessage to the VFP from the trigger instead of an error message so the message is shown on the VFP page with input fields

Here is my trigger:

trigger accountSearchTrg on Contact (before insert,before update) {
    List<Account> CheckAcc =[SELECT id, (SELECT Splits__c FROM Contacts) FROM Account WHERE id IN (SELECT AccountId
    FROM Contact  WHERE Splits__c=true)];

    for (Contact c : Trigger.New) {
        if(CheckAcc.size()>1) {             
            c.AddError('Not Possible');
        }
    }     
}
  • I would worry about fixing your trigger first. As written, it does not do what you think it does. – sfdcfox Sep 23 '17 at 16:01
2
  • You can use ApexPages.Message in your trigger.
  • set a static variable in ControllerExtension before DML.
  • Add to Visualforce page.

see following pseudocode

for (Contact c : Trigger.New) {
    if(CheckAcc.size()>1)
 {
     if(ControllerExtension.staticVar != null)// code won't be invoked from standard layout
     {   
         ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Invalid Input.');
         ApexPages.addMessage(myMsg);
     }
     else
    {
        c.AddError('Not Possible');
    }
}  
4

Besides the probable problems with your trigger's logic, you shouldn't be trying to add a page message within a trigger. Instead, modify your page's controller as appropriate, usually by using ApexPages.addMessages():

try {
    update contactList;
} catch(DMLException e) {
    ApexPages.addMessages(e);
}

This will prevent the default error screen and allow you to present the errors in an apex:pageMessages element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.