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
ravikanth321ravikanth321 

Validation Error message not showing on Visualforce Page:: I have a validation rule on ssn field on contact object for invalid format,But if i save contact record with invalid format ..Validation error message not showing on Visualforc page.

ApexClass::::
public class ActiveContactEditController{

    public Id recordTypeId{get;set;}
    public Id contactId{get;set;}
    public Contact con;
    public String profileName{get;set;}
    public Contact con1{get;set;}
    private ApexPages.StandardController sc;
    public Boolean editFlag{get; set;}
    public set<String> setOfUserPermissionSets{get;set;}
    public string mulId;
    public string mulId2;
    private List<sObject> duplicateRecords;
    private final Contact contact;
    public boolean hasDuplicateResult{get;set;}
    
    public boolean save_dup {get;set;}
    public boolean save_dup_ignore {get;set;}
    public boolean save_dup_ignorenew {get;set;}
    public boolean Test {get;set;}
        
    public ActiveContactEditController(ApexPages.StandardController controller){
    
    save_dup = false;
    save_dup_ignore = false;
    save_dup_ignorenew = false;
    Test = true;
    
     // Define the values for the contact you’re processing based on its ID
        Id id = ApexPages.currentPage().getParameters().get('id');
        this.contact = (id == null) ? new Contact() :
            [SELECT Id, FirstName, LastName
             FROM Contact WHERE Id = :id];
       
        // Initialize empty list of potential duplicate records
        this.duplicateRecords = new List<sObject>();
        this.hasDuplicateResult = false;
    
    
        this.sc = controller;
        con1 = new Contact();
       
         
        List<Schema.RecordTypeInfo> infos = Schema.SObjectType.Contact.RecordTypeInfos;
        Id defaultRecordTypeId;
        editFlag = false;
        //check each one
        for (Schema.RecordTypeInfo info : infos) {
          
          if (info.DefaultRecordTypeMapping) {
            
            defaultRecordTypeId = info.RecordTypeId;
            
            mulId = defaultRecordTypeId;
            mulId2 = mulId.substring(0,mulId.length()-3);
            
            system.debug('defaultRecordTypeId ' + mulId2);
          }
        }

        if(Apexpages.currentpage().getparameters().get('RecordType') != NULL){
        
            recordTypeId = Apexpages.currentpage().getparameters().get('RecordType');
            system.debug('******* recordTypeId ******  ' + recordTypeId );
           
            if(String.valueOf(recordTypeId).contains(Label.Active_RecordTypeID))
            con1.Active__c = true;
            
            if(String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID))
            con1.Small_Market__c = true;
         
            
        }
        if(Apexpages.currentpage().getparameters().get('Id') != NULL){
        
            contactId = Apexpages.currentpage().getparameters().get('Id');
            system.debug('contactId ' + contactId );
            con = [SELECT RecordtypeId from contact where id =: contactId];
            recordTypeId = con.RecordtypeId;
            
           
            
            if(contactId != null)
            editFlag = true;
        }
        if(recordTypeId == NULL){
        
            //recordTypeId = defaultRecordTypeId;
            recordTypeId  = String.valueOf(mulId2) ;
            system.debug('testing mulid '+recordTypeId  );
            system.debug('testing mulid '+mulId2);
            con1.Active__c = true;
            con1.Customer_Type__c = 'Active-Primary';
            con1.Input_Type__c = 'Manual';
            system.debug('con1.Customer_Type__c'+con1.Customer_Type__c);
            system.debug('con1.Input_Type__c'+con1.Input_Type__c);
        }
        
    }
    
    
    public List<sObject> getDuplicateRecords() {
        return this.duplicateRecords;
    }
 
    public boolean getRedirect(){
 
        if((recordTypeId != Label.Active_RecordTypeID || recordTypeId != Label.SM_Customer_RecordTypeID) && contactId == NULL){
        
            return true;
        }
        else{
        
            return false;
        }
    }
    
    public PageReference nextPage(){
    
        String ContactName;
        String relatedToFieldId = 'CF'+Label.Related_to_field_id+'_lkid';
        Id parentId = Apexpages.currentpage().getparameters().get(relatedToFieldId);
        if(parentId!= NULL){
        Contact conObj = [SELECT Salutation,FirstName,MiddleName, LastName from Contact where id =: parentId];
         /*** Forming Contact fullname  to use in URL ***/                  
         String Salutation = '';
         String FirstName = '';
         String MiddleName = '';
         String LastName = '';
         
         if(conObj.Salutation != NULL )
          Salutation = conObj.Salutation + '+';
         
         if(conObj.FirstName != NULL )
          FirstName = conObj.FirstName + '+';
        
         if(conObj.MiddleName != NULL )
          MiddleName = conObj.MiddleName + '+';
          
          LastName = conobj.LastName;
          
          ContactName = Salutation + FirstName + MiddleName + LastName;
         }
        system.debug('recordTypeId '+ recordTypeId );
        // Added '!String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID)' for small Market Wave 1
        if(recordTypeId != NULL && parentId != NULL && (!String.valueOf(recordTypeId).contains(Label.Active_RecordTypeID) && !String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID) ) && !String.valueOf(recordTypeId).contains(Label.Active_Retiree_RecordTypeId) && contactId == NULL){
        
            system.debug('Error1');
            PageReference pRef = new PageReference('/003/e?RecordType='+recordTypeId+'&CF'+Label.Related_to_field_id+'='
              +ContactName+'&'+relatedToFieldId+'='+parentId + '&nooverride=1');

            return pRef;
        }
        
        // Added '!String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID)' for small Market Wave 1
        else if(recordTypeId!= NULL && parentId == NULL && (!String.valueOf(recordTypeId).contains(Label.Active_RecordTypeID) && !String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID)) && !String.valueOf(mulId2).contains(Label.Active_Retiree_RecordTypeId) && contactId == NULL){
          system.debug('Error2 ' + recordTypeId);
         
          PageReference pRef = new PageReference('/003/e?RecordType='+recordTypeId+'&nooverride=1');
          
          return pRef;
        }
        
        // Added '!String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID)' for small Market Wave 1
        if(contactId != NULL && (!String.valueOf(recordTypeId).contains(Label.Active_RecordTypeID) && !String.valueOf(recordTypeId).contains(Label.SM_Customer_RecordTypeID)) && !String.valueOf(recordTypeId).contains(Label.Active_Retiree_RecordTypeId)){
         system.debug('Error3');
            PageReference pRef = new PageReference('/'+contactId+'/e?&nooverride=1'+'%2F'+contactId+'&retURL='+contactId);
            return pRef;
        }
        else if(contactId != NULL && String.valueOf(recordTypeId).contains(Label.Active_Retiree_RecordTypeId) && (setOfUserPermissionSets.contains('MM_Read_Only') || setOfUserPermissionSets.contains('MM_RET_Account_Manager') || setOfUserPermissionSets.contains('MM_RET_BC') || setOfUserPermissionSets.contains('MM_RET_Claims_Analyst') || setOfUserPermissionSets.contains('MM_RET_Claims_Manager') || setOfUserPermissionSets.contains('MM_RET_Manager') || setOfUserPermissionSets.contains('MM_RET_Quality_Assurance') || setOfUserPermissionSets.contains('MM_RET_Team_Lead') || setOfUserPermissionSets.contains('MM_SM_OSD'))){
         system.debug('Error4');
            PageReference pRef = new PageReference('/'+contactId+'/e?&nooverride=1&retURL=/'+contactId);
            return pRef;
        }
        else if(contactId == NULL && String.valueOf(mulId).contains(Label.Active_Retiree_RecordTypeId) && (setOfUserPermissionSets.contains('MM_Read_Only') || setOfUserPermissionSets.contains('MM_RET_Account_Manager') || setOfUserPermissionSets.contains('MM_RET_BC') || setOfUserPermissionSets.contains('MM_RET_Claims_Analyst') || setOfUserPermissionSets.contains('MM_RET_Claims_Manager') || setOfUserPermissionSets.contains('MM_RET_Manager') || setOfUserPermissionSets.contains('MM_RET_Quality_Assurance') || setOfUserPermissionSets.contains('MM_RET_Team_Lead') || setOfUserPermissionSets.contains('MM_SM_OSD'))){
         system.debug('Error5');
            PageReference pRef = new PageReference('/003/e?RecordType='+recordTypeId+'&nooverride=1&retURL=/003/o');
            return pRef;
        }
        else{
         system.debug('Error6');
            return NULL;
        }
    }

    public boolean validateDobandsocial(Contact conObj){
        Id acctId =conObj.AccountId;
        Date birthDt= conObj.DOB__c;
        String ssn = conObj.Social_Security_Number__c;
        Account accObj = [SELECT Id,Small_Market__c,Active__c,Client_Type__c from Account where id =: acctId];
        If (accObj.Active__c && (String.isBlank(String.valueOf(conObj.DOB__c)) || String.isBlank(conObj.Social_Security_Number__c))){
            return false;
        }else if (accObj.Small_Market__c && accObj.Client_Type__c != 'Brokerage' && (String.isBlank(String.valueOf(conObj.DOB__c)) || String.isBlank(conObj.Social_Security_Number__c))) {
            return false;
        }else if (accObj.Small_Market__c && accObj.Client_Type__c == 'Brokerage' && (String.isBlank(String.valueOf(conObj.DOB__c)) || String.isBlank(conObj.Social_Security_Number__c))) {
            return true;
        }else {
            return true;
        }

     }

    public pageReference Test(){
      hasDuplicateResult = false ;  
    Boolean stayOnpage = false;
    Contact conObj =(Contact) sc.getRecord();    
    boolean validateResult =  validateDobandsocial(conObj);
     try{
        if(validateResult){
            if(contactId == NULL){
                stayOnpage = Test2(conObj);
               // insert conObj;
                }
            else{
               // stayOnpage = Test2(conObj);          
                update conObj;
               }
      
       if(stayOnPage == true)
       {
        save_dup_ignore = true;
        save_dup = true;
        save_dup_ignorenew = true;

        Test = false;
        return null;
       }
       else{
              
        PageReference saveAndRedirectPage = new PageReference('/apex/ActiveContactEditRedirectPage');
        saveAndRedirectPage.setRedirect(true);
        saveAndRedirectPage.getParameters().put('id', conObj.id);
        saveAndRedirectPage.getParameters().put('name', conObj.name);
        return saveAndRedirectPage;}
       }else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'BirthDate and/or SSN can not be blank'));
            return null;
        }
    }catch(Exception ex){
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'testvali1'+ex.getdmlMessage(0)));
    return null;
    }
 
    }
    
    public Boolean Test2(Contact conObj){

    hasDuplicateResult = true ;
 
        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = true;
        dml.DuplicateRuleHeader.runAsCurrentUser = true;
         //Contact conObj =(Contact) sc.getRecord();
         
        Database.SaveResult saveResult = Database.insert(conObj, false);
      
        system.debug('The Test Debug after contact save on  savedupe');
        
       
         if (!saveResult.isSuccess()) {
         system.debug('The Test Inside after success savedupe');
            for (Database.Error error : saveResult.getErrors()) {
                // If there are duplicates, an error occurs
                // Process only duplicates and not other errors
                //   (e.g., validation errors)
                if (error instanceof Database.DuplicateError) {
                    // Handle the duplicate error by first casting it as a
                    //   DuplicateError class
                    // This lets you use methods of that class
                    //  (e.g., getDuplicateResult())
                    Database.DuplicateError duplicateError =
                            (Database.DuplicateError)error;
                    Datacloud.DuplicateResult duplicateResult =
                            duplicateError.getDuplicateResult();
                    
                    // Display duplicate error message as defined in the duplicate rule
                    ApexPages.Message errorMessage = new ApexPages.Message(
                            ApexPages.Severity.ERROR, 'Duplicate Error: ' +
                            duplicateResult.getErrorMessage());
                    ApexPages.addMessage(errorMessage);
                    
                    // Get duplicate records
                    this.duplicateRecords = new List<sObject>();

                    // Return only match results of matching rules that
                    //  find duplicate records
                    Datacloud.MatchResult[] matchResults =
                            duplicateResult.getMatchResults();

                    // Just grab first match result (which contains the
                    //   duplicate record found and other match info)
                    Datacloud.MatchResult matchResult = matchResults[0];

                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();

                    // Add matched record to the duplicate records variable
                    for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        this.duplicateRecords.add(matchRecord.getRecord());
                    }
                    this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
                }
            }
            
            //If there’s a duplicate record, stay on the page
            //return null;
            return (true);
        }
        
        /******* END *******/  
        else
        return (false);

    }

}


 
ravikanth321ravikanth321
VisualforcePage::
Visualforce Page::
<apex:page standardcontroller="Contact" action="{!nextPage}" extensions="ActiveContactEditController">
<apex:Messages />



 <!--get the session id;-->
    <script type="text/javascript">__sfdcSessionId = '{!$Api.Session_Id}';</script>
    <!--used the ajax toolkit library -->
    <script src="/soap/ajax/35.0/connection.js"></script>
    <!--used the jquery library -->
    <apex:includeScript value="{!$Resource.JqueryLib}"/>
    
    <style>
 
</style>

    <apex:sectionheader title="{!$ObjectType.Contact.label} Edit" subtitle="{!IF(ISNULL(Contact.Name), 'New Contact',Contact.Name)}"/>
   
    <apex:form id="conEdit">
    <apex:pageMessages />
        <apex:pageBlock title="Duplicate Records" rendered="{!hasDuplicateResult}">
         
            <apex:pageBlockTable value="{!duplicateRecords}" var="item">
                <apex:column >
                    <apex:facet name="header">Name</apex:facet>
                    <apex:outputLink value="/{!item['Id']}">{!item['Name']}</apex:outputLink>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Owner</apex:facet>
                    <apex:outputField value="{!item['OwnerId']}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Last Modified Date</apex:facet>
                    <apex:outputField value="{!item['LastModifiedDate']}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
 
        <apex:pageblock mode="edit" id="pgblk" title="{!$ObjectType.Contact.label} Edit">
         
            <apex:pageblockbuttons >
                <apex:commandbutton value="Save" rendered="{!(IF(Contact.Input_Type__c=='Manual', true, false) || contactId == NULL ) && editFlag == false && Test=true}"  action="{!Test}" id="save" />
                 <apex:commandbutton value="Cancel" action="{!Cancel}"/>
                 <apex:commandButton value="savedupe(Ignore)" action="{!Test3}" styleclass="Disab2" rendered="{!save_dup_ignore}" id="sdi"/>
          
            </apex:pageblockbuttons>
            
            <!-- **********   [Record Type : Active ]   **********  -->
            <apex:outputpanel rendered="{!IF(Contact.Input_Type__c!='Manual' && contactId != NULL, true, false) }">
                <br/>
                <apex:outputlabel value="You don't have permission to edit this Contact."/>
                
            </apex:outputpanel> <br/>
            <apex:outputpanel rendered="{!IF(Contact.Input_Type__c=='Manual', true, false) || contactId == NULL}">
         
                <apex:pageblocksection title="Contact Information" showheader="true" columns="2">
                 
                    <apex:pageBlockSection columns="1">
                 
                     
                        <apex:inputfield value="{!Contact.Salutation}" required="false" />
                        <apex:inputfield value="{!Contact.FirstName}" required="true" />  
                        <apex:inputfield value="{!Contact.LastName}" required="true"  />   
                                                                                                                                                          
                    </apex:pageBlockSection>
 
                </apex:pageblocksection>
                
            </apex:outputpanel>
        </apex:pageblock>
        
   
    </apex:form>
    
    
     <script type="text/javascript">
    
        $j=jQuery.noConflict();
        
        <!--after page is rendered for edit benefit -->
        $j(document).ready(function(){
     
            console.log('hi');
            getPlanName();
        });
    
    </script>
 
</apex:page>
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Try replacing from
<apex:Messages />
To
<apex:pageMessages id="showmsg" />
And then in each command button or action where there is a possibility of displaying an error you have to add to your reRender attribute the apex:pageMessages id:
<apex:commandButton value="savedupe(Ignore)" action="{!Test3}" styleclass="Disab2" rendered="{!save_dup_ignore}" id="sdi" reRender="showmsg" />

Hope to have helped!

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.

 
ravikanth321ravikanth321
Hi Zuingllo tried,Its not working :-(