You need to sign in to do that
Don't have an account?
Trapping Trigger error in controller extension
In my controller extension, I have my own save method:
public PageReference mysave() { baseController.save(); PageReference pageRef = new PageReference('/'+scorecard.Project__c); return pageRef; }
I also have a trigger that make sure I have only one relation to the parent which uses AddError:
trigger LimitScoreCardLink on symbiosis__Criteria_Scorecard__c (before insert, before update) { //Validate that only one BusinessCase can be associate with a project symbiosis__Criteria_Scorecard__c [] TheEntries; TheEntries = trigger.new; for(symbiosis__Criteria_Scorecard__c aCard: TheEntries ) { if (aCard.symbiosis__Project__c != null)
{ List<symbiosis__Criteria_Scorecard__c> TheScoreCardofThisProject = new List<symbiosis__Criteria_Scorecard__c>(); TheScoreCardofThisProject = [ select Id from symbiosis__Criteria_Scorecard__c where symbiosis__Project__c = :aCard.symbiosis__Project__c and Id != :aCard.Id ]; if (!TheScoreCardofThisProject.isEmpty()) { aCard.addError('The selected project already have a Scorecard attached.'); } } } }
This works with standard controller and display the error, but with the extension, how do I trap this error and make sure it displays?
Use a Try{
save()
}
Catch (Exception e){
ApexPages.addError(new ApexPages.Message(ApexPages.Severity.ERROR, 'I found an error'));
}
If you expect other exceptions besides the one that comes from the trigger, make the Exception you throw in the trigger your own class extending exception and then just catch that (rather than all exceptions)
try creating the Custom exception I talked about (a new class that extends Exception) and then throw a newly instantiated exception in your trigger. I don't think the way you are doing it 'bubbles' up
Same thing the exception is not catched:
public PageReference mysave()
{
try
{
baseController.save();
}
catch (MyException ex)
{
ApexPages.addMessages(ex);
return null;
}
PageReference pageRef = new PageReference('/'+scorecard.Project__c);
return pageRef;
}
In the trigger:
if (!TheScoreCardofThisProject.isEmpty())
{
throw new MyException('The selected project already have a Scorecard attached.');
}
Here's a gotcha I've noticed. Let's see if you're impacted by it:
Is your pageAction called from a command button? If so, do you have a apex:pageMessages section in your vf page? If both of these are true, you'll need to add a rerender target of the apex:pageMessages on your command button. If you don't, the error message will not be displayed.
like so:
<apex:page controller="MyObject__c" extensions="MyControllerExtension">
<apex:form>
<apex:pageBlock>
<apex:pageMessages id="errorMessages" />
<apex:commandButton action="{!save}" rerender="errorMessages" />
</apex:pageBlock>
</apex:form>
</apex:page>