+ Start a Discussion
Jean Grey 10Jean Grey 10 

Display Error Message from Unique Field Error

We have a unique field on an object, populated by workflow (datestamp + userId), which prevents a user from submitting two records on the same day. I'd like to display an error message on the visualforce input page, but the normal error message approaches don't seem to be working. Is there some special way I need to display this error? Here is my controller:
public class NewDailyForecast {
           
            public Daily_Forecast__c fc {get;set;}
            public String userId {get;set;}
            public Date todayDate {get;set;}
            public String dailyType {get;set;}
            public String weeklyType {get;set;}
            public String fName {get;set;}
            public double fAmount {get;set;}
            public String recType {get;set;}
            public List<Daily_Forecast__c> thisWeekDaily {get;set;}
            public List<Daily_Forecast__c> thisWeekWeekly {get;set;}
            public List<Daily_Forecast__c> checkUnique {get;set;}

            //set up controller & extension for vf page
            ApexPages.StandardSetController setCon;

            public NewDailyForecast(ApexPages.StandardSetController controller) {
                setCon = controller;
            }

            public void getValues(){
                //get logged in user
                userId = UserInfo.getUserId();
                system.debug('userId '+userId);
                
                //get today's date
                todayDate = system.today();
                system.debug('todayDate '+todayDate);
                
                //get record type
                dailyType = [SELECT Id FROM RecordType WHERE Name = 'Daily Forecast'].Id;
                weeklyType = [SELECT Id FROM RecordType WHERE Name = 'Weekly Forecast'].Id;
                system.debug('dailyType '+dailyType);
                system.debug('weeklyType '+weeklyType);
                    
                fName = userId + todayDate;
                    
                fAmount=0;

                //new forecast record on page
                fc = new Daily_Forecast__c (RecordTypeId = dailyType, Date__c = todayDate, Forecast_Amount__c = fAmount, User__c = userId);
                system.debug('fc '+fc);
                
                //list of related forecast records
                thisWeekDaily = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c, User__r.UserRole.Name, User__r.Territory__c, Forecast_Amount__c, RecordTypeId, RecordType.Name 
                        FROM Daily_Forecast__c WHERE User__c = :userId AND Date__c = THIS_WEEK AND RecordTypeId = :dailyType ORDER BY Date__c ASC]);
                system.debug('thisWeekDaily '+thisWeekDaily);
                thisWeekWeekly = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c, User__r.UserRole.Name, User__r.Territory__c, Forecast_Amount__c, RecordTypeId, RecordType.Name 
                        FROM Daily_Forecast__c WHERE User__c = :userId AND Date__c = THIS_WEEK AND RecordTypeId = :weeklyType ORDER BY Date__c ASC]);        
                system.debug('thisWeekWeekly '+thisWeekWeekly);        
            }
            
            public PageReference saveRecord(){
            //error catching method 1: build list to match existing and throw error if list>0
            //this doesn't work
                checkUnique = new List<Daily_Forecast__c>([SELECT Id, Date__c, User__c FROM Daily_Forecast__c WHERE Date__c = :fc.Date__c AND User__c = :fc.User__c]);
        /*        if(checkUnique.size()>0){
                    system.debug('checkUnique '+checkUnique);
                    ApexPages.Message myFatalMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Duplicate record created. Please try again');
                    ApexPages.addMessage(myFatalMsg);
                    system.debug('fatal error '+myFatalMsg);
                    ApexPages.Message myErrorMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message');
                    ApexPages.addMessage(myErrorMsg);
                    system.debug('error '+myErrorMsg);
                }
                insert fc;
        */
                //error catching method 2: try insert and catch exception
                //This doesn't work either
                try {
                    insert fc;
                }
                catch(DMLException e)
                {
                    for(Daily_Forecast__c df :thisWeekDaily){
                        df.addError('Duplicate entry not allowed');
                    }
                    system.debug(e);
                    ApexPages.addMessages(e);
                    ApexPages.Message myFatalMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Duplicate record created. Please try again');
                    ApexPages.addMessage(myFatalMsg);
                    return null;
                }
                return new pageReference( '/' + fc.id );
            }
        }

And vf page:
 
<apex:page standardController="Daily_Forecast__c" extensions="NewDailyForecast" recordSetVar="forecasts" tabStyle="Daily_Forecast__c" sidebar="false" action="{!getValues}">
            <apex:form >
            <apex:pageblock >
              <apex:messages />

            </apex:pageblock>        
            <apex:pageBlock title="Create New Forecast" mode="edit">
                    <apex:pageBlockButtons >
                        <apex:commandButton value="Save" action="{!saveRecord}" rerender="error"/>
                        <apex:commandButton value="Cancel" action="{!cancel}"/>
                    </apex:pageBlockButtons>
                <apex:pageBlockSection >
                    <apex:inputField label="Forecast Type" value="{!fc.RecordTypeId}" id="recType" />
                    <apex:inputField label="Amount" value="{!fc.Forecast_Amount__c}" id="fAmount" />
                    <apex:inputField label="User Name" value="{!fc.User__c}" id="fUser" />
                    <apex:inputField label="Date" value="{!fc.Date__c}" id="fDate" />
                </apex:pageBlockSection>
            </apex:pageBlock>
            <apex:pageBlock title="This Week's Forecast">
                <apex:pageBlockSection >
                    <apex:pageBlockTable id="thisWeek" value="{!thisWeekDaily}" var="d" >
                        <apex:column headerValue="Day"><apex:outputText value="{0, date, EEEE}">
                                <apex:param value="{!d.Date__c}" /> 
                            </apex:outputText></apex:column>
                        <apex:column headerValue="Forecast Amount"><apex:outputField value="{!d.Forecast_Amount__c}"/></apex:column>
                        <apex:column headerValue="Type"><apex:outputField value="{!d.RecordType.Name}" /></apex:column>
                    </apex:pageBlockTable>
                    <apex:pageBlockTable id="thisWeekWeekly" value="{!thisWeekWeekly}" var="w" >
                        <apex:column headerValue="Day"><apex:outputText value="{0, date, EEEE}">
                                <apex:param value="{!w.Date__c}" /> 
                            </apex:outputText></apex:column>
                        <apex:column headerValue="Forecast Amount"><apex:outputField value="{!w.Forecast_Amount__c}"/></apex:column>
                        <apex:column headerValue="Type"><apex:outputField value="{!w.RecordType.Name}" /></apex:column>
                    </apex:pageBlockTable>            
                </apex:pageBlockSection>
            </apex:pageBlock>
            </apex:form>
        </apex:page>

What is the correct way to catch and display the unique/duplicate error message on the vf page? Without any error handling i get the expected INSERT FAILED error screen, which is not user-friendly. With the exception catching above, no message shows at all. How can I program the exception handling to display a user-friendly error message? Thanks in advance.
Dmitry OfitserovDmitry Ofitserov
Hi Jean,
Have you tried to put <apex:messages /> block right after the opening <apex:page....> element (I mean putting it outside of the form as the first element of the page) ?
Jean Grey 10Jean Grey 10
I found the issue. <apex:commandButton value="Save" action="{!saveRecord}" rerender="error"/> I removed the rerender attribute and the messages show up now.