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
Force2b_MikeForce2b_Mike 

Display Error on VisualForce Page via a Controller Extension

I have a fairly simple VF page with an [Undelete] button that calls a method in a controller extension. If the button action fails, I want to be able to display a message at the top of the screen while still showing the original record below the message. Unfortunately, no matter what I try I get the error message but without the original record. I must be doing something wrong in setting the return for the method, but I've tried a number of different variations each with the same result, or just displaying the original message without any error.

 

 

 

VisualForce Page:

 

<apex:page standardController="DeleteLog__c" extensions="DeleteLog_extension"> <apex:pageBlock > <apex:messages /> <apex:pageBlockButtons > <apex:form > <apex:commandButton action="{!unDeleteRecord}" title="Undelete" value="Undelete"/> <apex:outputText value="{!DeleteLog__c.ObjectID__c}" rendered="false"/> </apex:form> </apex:pageBlockButtons> <apex:detail /> </apex:pageBlock> </apex:page>

 

 

Controller Extension:

 

public class DeleteLog_extension {

 

private final DeleteLog__c delLog;
private PageReference pageRef = ApexPages.currentPage();

 

public DeleteLog_extension(ApexPages.StandardController stdController) {
this.delLog = (DeleteLog__c)stdController.getRecord();
}

 

public PageReference unDeleteRecord() { Try { List<string> IDs = New List<String>(); IDs.add(this.delLog.ObjectID__c); database.undelete(IDs); PageReference obj = new PageReference('/' + delLog.ObjectID__c); obj.setRedirect(true); return obj; } Catch(DMLException ex) { string thisid = pageRef.getParameters().get('id'); System.Debug('ID =' + thisid); System.Debug('CurrentPage =' + pageRef.getUrl()); PageReference obj = new PageReference(pageRef.getUrl() + '?ID=' + thisid); System.Debug('New URL =' + obj.getUrl()); for (Integer i = 0; i < ex.getNumDml(); i++) { ApexPages.addMessage(new ApexPages.Message ApexPages.Severity.ERROR, ex.getDmlMessage(i))); } pageRef.setRedirect(false); return pageRef; }

}

 

Thanks,

 

Mike

 

Best Answer chosen by Admin (Salesforce Developers) 
Force2b_MikeForce2b_Mike

I was able to get this to work by adding the  Apex:PageMessages tag directly after the Apex:Page tag.

 

Mike

All Answers

angusgrantangusgrant
Hi I also have this issue and am yet to work it out.
Force2b_MikeForce2b_Mike

I was able to get this to work by adding the  Apex:PageMessages tag directly after the Apex:Page tag.

 

Mike

This was selected as the best answer
KaityKaity

Thank you. It works for me as well.