• Amar J
  • NEWBIE
  • 10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
We have a custom new contact visualforce page which uses visualforce component.
Recently we planned on implmenting Duplicate Matching rules to show Duplicate records(if any) up on saving a new record. 

we used the following link provided by Salesforce to write our custom visualforce logic to show duplicate matching records.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Datacloud_DuplicateResult.htm

We wrote the code in the custom component and component controller. The problem is that upon save it is not rendering the duplicateresult table(This table shows the duplicate records if any). 

Contact Visaulforce Page
<apex:page standardController="Contact" extensions="NewContactPageWithAddressController">
    <apex:sectionHeader title="New Contact"/>
    Contacts not associated with accounts are private and cannot be viewed by other users or included in reports.
    
    <c:ContactForms contact="{!contact}" redirect="true"/>
</apex:page>
Contact Controller
public with sharing class NewContactPageWithAddressController {
    public Contact contact{get;set;}
    public ApexPages.StandardController standardController {get;set;}
    
    public NewContactPageWithAddressController(ApexPages.StandardController controller) {
        standardController = controller;
        this.contact = new contact();
        this.contact.accountId = ApexPages.currentPage().getParameters().get('accid');
    }   
}

Visualforce Component: Contactform 
 
<apex:component controller="ContactFormsCont" allowDML="true">
	<apex:attribute name="contact" assignTo="{!mainContact}" description="The contact to be edited" type="Contact" required="true" />
	<apex:attribute name="redirect" assignTo="{!redirectPage}" description="Set true if the page should redirect to the contact after saving" type="Boolean" />
	<apex:attribute name="onSave" description="Javascript to be executed when record successfully saves" type="String" />
  <apex:attribute name="rerenderable" description="Hides fields that can't be rerendered, i.e.: rich text fields" type="Boolean" />
    <apex:form >
        <apex:pagemessages id="messages"/> 
         <apex:pageBlock title="Duplicate Records" rendered="{!hasDupResult}" id="DupRecords" >
            <apex:pageMessages />
            <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 title="Contact Edit">
            
            <apex:pageBlockSection title="Contact Information" collapsible="False">
               <!-- <apex:outputLabel value="Contact Owner {!$User.FirstName}"></apex:outputLabel> -->
           <apex:pageBlockSectionItem >
               <apex:outputlabel value="Contact Owner"/>
               <apex:outputText value="{!$User.FirstName &' '& $User.LastName}"/>
               <!--<apex:outputLabel value=""> </apex:outputLabel>-->
              </apex:pageBlockSectionItem>
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Contact_Information}" var="ContactInformation">
                   <apex:inputField value="{!mainContact[ContactInformation]}" required="{!ContactInformation.required}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
			<apex:pageBlockSection Id="ContactAddress" Title="Address Infromation">
                <apex:pageBlockSectionItem >
                    <apex:OutputLabel value="Address"/>
                    
                    <apex:actionRegion >
                        <apex:InputField value="{!contactAddress.Address__c}" required="false">
                            <apex:actionSupport event="onchange" immediate="false" action="{!selectAddress}" rerender="ContactAddress"/>
                        </apex:InputField>
                    </apex:actionRegion>    
                    
                </apex:pageBlockSectionItem>
                
                <apex:OutputField value="{!address.Name}" rendered="{!contactAddress.Id != null}"/><apex:outputField value="{!address.OwnerId}" />
                
                <apex:InputField value="{!address.Address_Name__c}" rendered="{!!addressSelected}"/>                
                <apex:outputField value="{!address.Address_Name__c}" rendered="{!addressSelected}"/>    <apex:OutputField value="{!contactAddress.Contact__c}"/>    
                <apex:InputField value="{!address.Address_Line_1__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.Address_Line_1__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Active__c}" />
                <apex:InputField value="{!address.Address_Line_2__c}" rendered="{!!addressSelected}"/>          
                <apex:OutputField value="{!address.Address_Line_2__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Physical__c}"/>
                <apex:InputField value="{!address.Address_Line_3__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_3__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Mail_To__c}"/>
                <apex:InputField value="{!address.Address_Line_4__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_4__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Primary_Mail_To__c}"/>
                <apex:InputField value="{!address.City__c}" rendered="{!!addressSelected}" />            
                <apex:OutputField value="{!address.City__c}" rendered="{!addressSelected}"/>            <apex:OutputPanel />
                <apex:InputField value="{!address.Country__c}" rendered="{!!addressSelected}" />         
                <apex:OutputField value="{!address.Country__c}" rendered="{!addressSelected}"/>         <apex:OutputPanel />
                <apex:InputField value="{!address.State_Province__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.State_Province__c}" rendered="{!addressSelected}"/>  <apex:OutputPanel />
                <apex:InputField value="{!address.Postal_Code__c}" rendered="{!!addressSelected}"/>     
                <apex:OutputField value="{!address.Postal_Code__c}" rendered="{!addressSelected}"/>     <apex:OutputPanel />
                
                <apex:pageBlockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified Date"/>
                    <apex:OutputField value="{!address.LastModifiedDate}" />
                </apex:pageBlockSectionItem>
                <apex:pageblockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified By"/>
                    <apex:OutputField value="{!address.LastModifiedBy.Name}" />
                </apex:pageblockSectionItem>
			</apex:PageBlockSection>
            
             <apex:pageBlockSection title="Strategic Account Management">
                <apex:repeat value="{!$ObjectType.Contact.FieldSets.Strategic_Account_Management}" var="StrategicAccountManagement">
                   <apex:inputField value="{!mainContact[StrategicAccountManagement]}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Additional Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Additional_Information}" var="AdditionalInformation">
                   <apex:inputField value="{!mainContact[AdditionalInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="DCW Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.DCW_Information}" var="DCWInformation">
                   <apex:inputField value="{!mainContact[DCWInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="Intelligent Equipment User Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information}" var="IntelligentEquipmentUserInformation">
                   <apex:inputField value="{!mainContact[IntelligentEquipmentUserInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="System Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.System_Information}" var="SystemInformation">
                   <apex:inputField value="{!mainContact[SystemInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            
            <apex:PageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="DupRecords" status="actStatusId" oncomplete="if({!recordSaved}){{!onSave}}"/>
                <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Save & New" action="{!SaveandNew}" reRender="DupRecords" status="actStatusId2" rendered="{!redirectPage}"/>
                  <apex:actionStatus id="actStatusId2" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Cancel" action="{!sc.Cancel}" reRender="messages" immediate="True" rendered="{!redirectPage}"/>
            </apex:PageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:component>

Component Controller
public with sharing class ContactFormsCont {
    public Contact_Address__c contactAddress{
    	get{
    		if(contactAddress == null){
    			contactAddress = new Contact_Address__c(Primary_Mail_To__c = true, Active__c = true);
    		}
    		return contactAddress;
    	}
    	set;
    }
    public Address__c originalAddress{
    	get{
    		if(originalAddress == null){
    			originalAddress = new Address__c();
    		}
    		return originalAddress;
    	}
    	set;
    }
    public Address__c address{
    	get{
    		if(address == null){
    			address = new Address__c();
    			addressSelected = false;
    		}
    		return address;
    	}
    	set;
    }
    public boolean addressSelected{get;set;}

    public boolean redirectPage{
    	get{
    		if(redirectPage == null) return false;
    		else return redirectPage;
    	}
    	set;
    }

    public Boolean recordSaved {
    	get{
    		return recordSaved == null? false : recordSaved;
    	} set;
    }

	public ApexPages.StandardController sc{
		get{
			return new ApexPages.StandardController(new Contact());
		}
	}
    
    private List<Contact> duplicateRecords = new List<Contact>();
    
    public List<Contact> getDuplicateRecords(){
        return duplicateRecords;
    }
	
	Public Boolean hasDupResult{
        get{if(duplicateRecords.isEmpty()){
            return FALSE;
        } else {
            return TRUE;
        } 
           }
        set;

    }    

    public Contact mainContact{
    	get;
    	set{
	    	if(value != null && value.Id != null){
	    		if(mainContact != null && mainContact.Id == value.Id ) return;
                try{
    		    	mainContact = Database.query('SELECT ' + String.escapeSingleQuotes(queryFields) + ' FROM Contact WHERE Id = \''+value.Id+'\' LIMIT 1');
                } catch (QueryException e){return;}
		    	loadAddressData(mainContact.Id); 	
	    	} else if(value != null && value.Id == null){
                Boolean isChanged = mainContact != value;
	    		mainContact = value;
                if(isChanged){
                    contactAddress = null;
                    address = null;
                }
	    	} else {
	    		mainContact = value;
	    	}
        }
    }

    // Pulls primary contact address and it's corresponding address object from database
    public void loadAddressData(Id contactId){
    	List<Contact_Address__c> ctcAddrs = [SELECT Id, Name, Contact__c, Address__c, Active__c, Mail_To__c, Physical__c, Contact__r.AccountId, Primary_Mail_To__c, 
											    	Address__r.Address_Line_1__c, Address__r.Address_Line_2__c, Address__r.Address_Line_3__c, Address__r.Address_Line_4__c, 
											    	Address__r.City__c, Address__r.Country__c, Address__r.State_Province__c, Address__r.Postal_Code__c, Address__r.Name, 
											    	Address__r.OwnerId, Address__r.Address_Name__c, Address__r.Id, Address__r.DCW_ID__c, Address__r.Warehouse_Id__c, 
											    	Address__r.IE_ID__c, Address__r.State_Province_ISO_Code__c, Address__r.Country_ISO_Code__c, 
											    	Address__r.LastModifiedBy.Name, Address__r.LastModifiedDate, LastModifiedBy.Name, LastModifiedDate
											 FROM Contact_Address__c
											 WHERE Contact__c = :contactID AND Primary_Mail_To__c = true];
		if(ctcAddrs.size() == 1) contactAddress = ctcAddrs[0];
		else {contactAddress = null; return;}
		address = contactAddress.Address__r;
		addressSelected = true;
		originalAddress = new Address__c(  Address_Line_1__c = contactAddress.Address__r.Address_Line_1__c
										  , Address_Line_2__c = contactAddress.Address__r.Address_Line_2__c
										  , Address_Line_3__c = contactAddress.Address__r.Address_Line_3__c
										  , Address_Line_4__c = contactAddress.Address__r.Address_Line_4__c
										  , City__c = contactAddress.Address__r.City__c
										  , Country__c =  contactAddress.Address__r.Country__c
										  , State_Province__c = contactAddress.Address__r.State_Province__c
										  , Postal_Code__c = contactAddress.Address__r.Postal_Code__c
										  , Address_Name__c = contactAddress.Address__r.Address_Name__c
									  	  , IE_ID__c = contactAddress.Address__r.IE_ID__c
									  	  , DCW_ID__c = contactAddress.Address__r.DCW_ID__c
									  	  , Warehouse_Id__c = contactAddress.Address__r.Warehouse_Id__c
										  , State_Province_ISO_Code__c = contactAddress.Address__r.State_Province_ISO_Code__c
										  , Country_ISO_Code__c = contactAddress.Address__r.Country_ISO_Code__c
										  , Id = contactAddress.Address__r.Id
										  );


    }

    // Gets all fields used in the page for querying
    public String queryFields{
    	get{
    		if(queryFields == null){
    			queryFields = ''; // Fields not in fieldsets can be added here, separated by commas
    			List<Schema.FieldSetMember> allFieldSets = new List<Schema.FieldSetMember>();
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Contact_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Strategic_Account_Management.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Additional_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.DCW_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.System_Information.getFields());
    			for(Integer i = 0; i < allFieldSets.size(); i++){
    				if(!String.isEmpty(queryFields)) queryFields += ', ';
    				queryFields += allFieldSets[i].getFieldPath();
    			}
    		}
    		return queryFields;
    	}
    	set;
    }
    
    public PageReference selectAddress()
    {
        if(contactAddress.Address__c != null)
        {
            address = [select Address_Line_1__c
                            , Address_Line_2__c
                            , Address_Line_3__c
                            , Address_Line_4__c
                            , City__c
                            , Country__c
                            , State_Province__c
                            , Postal_Code__c
                            , Name
                            , OwnerId 
                            , Address_Name__c
                            , DCW_Id__c
                            , Warehouse_Id__c
                            , IE_ID__c
                            , State_Province_ISO_Code__c
                            , Country_ISO_Code__c
                            , LastModifiedBy.Name
                            , LastModifiedDate
                        from Address__c
                       where Id = :contactAddress.Address__c];
                       
            addressSelected = true;
            contactAddress.Active__c = true;
        }
        else
        {
            addressSelected = false;
            address = new Address__c();
            contactAddress = null;
        }
        
        return null;
    }
    
    public PageReference Save(){
	    PageReference pg;
        Id prevContId = mainContact.Id;
        Contact_Address__c prevContAdd = contactAddress.clone(true, true);
        Address__c prevOrigAdd = originalAddress.clone(true, true);
        Address__c prevAdd = address.clone(true, true);
        Savepoint sp = Database.setSavepoint();
        
         
		    recordSaved = false;
			
            If(mainContact.Id != NULL){
                update mainContact;
                if(addressSelected == false) originalAddress = null;
                if(contactAddress.Contact__c == null) contactAddress.Contact__c = mainContact.Id;
    
                AddressHelper.saveContactAddress(  new List<ContactAddressDetail.ContactAddressWrapper>()
                                                   , new List<ContactAddressDetail.AccountAddressWrapper>()
                                                   , originalAddress
                                                   , address
                                                   , contactAddress
                                                   , addressSelected);
    
                pg= new ApexPages.StandardController(mainContact).view();
                pg.setRedirect(true);
                recordSaved = true;
            
            
            	return redirectPage? pg : null;
            } else{
                Database.DMLOptions dml = new Database.DMLOptions(); 
                dml.DuplicateRuleHeader.allowSave = true;
                dml.DuplicateRuleHeader.runAsCurrentUser = true;
                Database.SaveResult saveResult = Database.insert(mainContact, dml);
                
                system.debug('mainContact is: '+ mainContact);
                system.debug('save result is: '+ saveResult);
                
            	if (!saveResult.isSuccess()) {
                	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                        
                        //duplicateRecords = new List<Contact>();
                        //hasDupResult = False;
                        // Return only match results of matching rules that find duplicate records
                        Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                        System.debug('Match Results: ' + matchResults);
                        // Just grab first match result (which contains the duplicate record found and other match info)
                        Datacloud.MatchResult matchResult = matchResults[0];
                        System.debug('Match Result: ' + matchResult);
                        Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
                        System.debug('matchRecords: ' + matchRecords);
                        // Add matched record to the duplicate records variable
                        for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        duplicateRecords.add((Contact)matchRecord.getRecord());
                        System.Debug('Final Duplicate Records: '+ duplicateRecords);
                    } 
                    this.hasDupResult = TRUE;
                    System.Debug('hasDupResult: '+ this.hasDupResult);
                    System.Debug('Final Duplicate Records: '+ duplicateRecords);
                }
                        
            
            }
            
            
        }
                //If there’s a duplicate record, stay on the page
                return null;
            }

            
    }
    
    public PageReference saveAndNew() {
        PageReference pg =  Page.NewContactPageWithAddress;
        pg.setRedirect(true);
        return save() == null ? null : pg;
    }
}

Please see the highlighted code which needs to rerender the page block in Visualforce component id = DupRecords.

Thanks for your help.
  • January 24, 2017
  • Like
  • 0
We have a custom new contact visualforce page which uses visualforce component.
Recently we planned on implmenting Duplicate Matching rules to show Duplicate records(if any) up on saving a new record. 

we used the following link provided by Salesforce to write our custom visualforce logic to show duplicate matching records.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Datacloud_DuplicateResult.htm

We wrote the code in the custom component and component controller. The problem is that upon save it is not rendering the duplicateresult table(This table shows the duplicate records if any). 

Contact Visaulforce Page
<apex:page standardController="Contact" extensions="NewContactPageWithAddressController">
    <apex:sectionHeader title="New Contact"/>
    Contacts not associated with accounts are private and cannot be viewed by other users or included in reports.
    
    <c:ContactForms contact="{!contact}" redirect="true"/>
</apex:page>
Contact Controller
public with sharing class NewContactPageWithAddressController {
    public Contact contact{get;set;}
    public ApexPages.StandardController standardController {get;set;}
    
    public NewContactPageWithAddressController(ApexPages.StandardController controller) {
        standardController = controller;
        this.contact = new contact();
        this.contact.accountId = ApexPages.currentPage().getParameters().get('accid');
    }   
}

Visualforce Component: Contactform 
 
<apex:component controller="ContactFormsCont" allowDML="true">
	<apex:attribute name="contact" assignTo="{!mainContact}" description="The contact to be edited" type="Contact" required="true" />
	<apex:attribute name="redirect" assignTo="{!redirectPage}" description="Set true if the page should redirect to the contact after saving" type="Boolean" />
	<apex:attribute name="onSave" description="Javascript to be executed when record successfully saves" type="String" />
  <apex:attribute name="rerenderable" description="Hides fields that can't be rerendered, i.e.: rich text fields" type="Boolean" />
    <apex:form >
        <apex:pagemessages id="messages"/> 
         <apex:pageBlock title="Duplicate Records" rendered="{!hasDupResult}" id="DupRecords" >
            <apex:pageMessages />
            <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 title="Contact Edit">
            
            <apex:pageBlockSection title="Contact Information" collapsible="False">
               <!-- <apex:outputLabel value="Contact Owner {!$User.FirstName}"></apex:outputLabel> -->
           <apex:pageBlockSectionItem >
               <apex:outputlabel value="Contact Owner"/>
               <apex:outputText value="{!$User.FirstName &' '& $User.LastName}"/>
               <!--<apex:outputLabel value=""> </apex:outputLabel>-->
              </apex:pageBlockSectionItem>
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Contact_Information}" var="ContactInformation">
                   <apex:inputField value="{!mainContact[ContactInformation]}" required="{!ContactInformation.required}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
			<apex:pageBlockSection Id="ContactAddress" Title="Address Infromation">
                <apex:pageBlockSectionItem >
                    <apex:OutputLabel value="Address"/>
                    
                    <apex:actionRegion >
                        <apex:InputField value="{!contactAddress.Address__c}" required="false">
                            <apex:actionSupport event="onchange" immediate="false" action="{!selectAddress}" rerender="ContactAddress"/>
                        </apex:InputField>
                    </apex:actionRegion>    
                    
                </apex:pageBlockSectionItem>
                
                <apex:OutputField value="{!address.Name}" rendered="{!contactAddress.Id != null}"/><apex:outputField value="{!address.OwnerId}" />
                
                <apex:InputField value="{!address.Address_Name__c}" rendered="{!!addressSelected}"/>                
                <apex:outputField value="{!address.Address_Name__c}" rendered="{!addressSelected}"/>    <apex:OutputField value="{!contactAddress.Contact__c}"/>    
                <apex:InputField value="{!address.Address_Line_1__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.Address_Line_1__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Active__c}" />
                <apex:InputField value="{!address.Address_Line_2__c}" rendered="{!!addressSelected}"/>          
                <apex:OutputField value="{!address.Address_Line_2__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Physical__c}"/>
                <apex:InputField value="{!address.Address_Line_3__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_3__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Mail_To__c}"/>
                <apex:InputField value="{!address.Address_Line_4__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_4__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Primary_Mail_To__c}"/>
                <apex:InputField value="{!address.City__c}" rendered="{!!addressSelected}" />            
                <apex:OutputField value="{!address.City__c}" rendered="{!addressSelected}"/>            <apex:OutputPanel />
                <apex:InputField value="{!address.Country__c}" rendered="{!!addressSelected}" />         
                <apex:OutputField value="{!address.Country__c}" rendered="{!addressSelected}"/>         <apex:OutputPanel />
                <apex:InputField value="{!address.State_Province__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.State_Province__c}" rendered="{!addressSelected}"/>  <apex:OutputPanel />
                <apex:InputField value="{!address.Postal_Code__c}" rendered="{!!addressSelected}"/>     
                <apex:OutputField value="{!address.Postal_Code__c}" rendered="{!addressSelected}"/>     <apex:OutputPanel />
                
                <apex:pageBlockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified Date"/>
                    <apex:OutputField value="{!address.LastModifiedDate}" />
                </apex:pageBlockSectionItem>
                <apex:pageblockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified By"/>
                    <apex:OutputField value="{!address.LastModifiedBy.Name}" />
                </apex:pageblockSectionItem>
			</apex:PageBlockSection>
            
             <apex:pageBlockSection title="Strategic Account Management">
                <apex:repeat value="{!$ObjectType.Contact.FieldSets.Strategic_Account_Management}" var="StrategicAccountManagement">
                   <apex:inputField value="{!mainContact[StrategicAccountManagement]}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Additional Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Additional_Information}" var="AdditionalInformation">
                   <apex:inputField value="{!mainContact[AdditionalInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="DCW Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.DCW_Information}" var="DCWInformation">
                   <apex:inputField value="{!mainContact[DCWInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="Intelligent Equipment User Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information}" var="IntelligentEquipmentUserInformation">
                   <apex:inputField value="{!mainContact[IntelligentEquipmentUserInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="System Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.System_Information}" var="SystemInformation">
                   <apex:inputField value="{!mainContact[SystemInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            
            <apex:PageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="DupRecords" status="actStatusId" oncomplete="if({!recordSaved}){{!onSave}}"/>
                <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Save & New" action="{!SaveandNew}" reRender="DupRecords" status="actStatusId2" rendered="{!redirectPage}"/>
                  <apex:actionStatus id="actStatusId2" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Cancel" action="{!sc.Cancel}" reRender="messages" immediate="True" rendered="{!redirectPage}"/>
            </apex:PageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:component>

Component Controller
public with sharing class ContactFormsCont {
    public Contact_Address__c contactAddress{
    	get{
    		if(contactAddress == null){
    			contactAddress = new Contact_Address__c(Primary_Mail_To__c = true, Active__c = true);
    		}
    		return contactAddress;
    	}
    	set;
    }
    public Address__c originalAddress{
    	get{
    		if(originalAddress == null){
    			originalAddress = new Address__c();
    		}
    		return originalAddress;
    	}
    	set;
    }
    public Address__c address{
    	get{
    		if(address == null){
    			address = new Address__c();
    			addressSelected = false;
    		}
    		return address;
    	}
    	set;
    }
    public boolean addressSelected{get;set;}

    public boolean redirectPage{
    	get{
    		if(redirectPage == null) return false;
    		else return redirectPage;
    	}
    	set;
    }

    public Boolean recordSaved {
    	get{
    		return recordSaved == null? false : recordSaved;
    	} set;
    }

	public ApexPages.StandardController sc{
		get{
			return new ApexPages.StandardController(new Contact());
		}
	}
    
    private List<Contact> duplicateRecords = new List<Contact>();
    
    public List<Contact> getDuplicateRecords(){
        return duplicateRecords;
    }
	
	Public Boolean hasDupResult{
        get{if(duplicateRecords.isEmpty()){
            return FALSE;
        } else {
            return TRUE;
        } 
           }
        set;

    }    

    public Contact mainContact{
    	get;
    	set{
	    	if(value != null && value.Id != null){
	    		if(mainContact != null && mainContact.Id == value.Id ) return;
                try{
    		    	mainContact = Database.query('SELECT ' + String.escapeSingleQuotes(queryFields) + ' FROM Contact WHERE Id = \''+value.Id+'\' LIMIT 1');
                } catch (QueryException e){return;}
		    	loadAddressData(mainContact.Id); 	
	    	} else if(value != null && value.Id == null){
                Boolean isChanged = mainContact != value;
	    		mainContact = value;
                if(isChanged){
                    contactAddress = null;
                    address = null;
                }
	    	} else {
	    		mainContact = value;
	    	}
        }
    }

    // Pulls primary contact address and it's corresponding address object from database
    public void loadAddressData(Id contactId){
    	List<Contact_Address__c> ctcAddrs = [SELECT Id, Name, Contact__c, Address__c, Active__c, Mail_To__c, Physical__c, Contact__r.AccountId, Primary_Mail_To__c, 
											    	Address__r.Address_Line_1__c, Address__r.Address_Line_2__c, Address__r.Address_Line_3__c, Address__r.Address_Line_4__c, 
											    	Address__r.City__c, Address__r.Country__c, Address__r.State_Province__c, Address__r.Postal_Code__c, Address__r.Name, 
											    	Address__r.OwnerId, Address__r.Address_Name__c, Address__r.Id, Address__r.DCW_ID__c, Address__r.Warehouse_Id__c, 
											    	Address__r.IE_ID__c, Address__r.State_Province_ISO_Code__c, Address__r.Country_ISO_Code__c, 
											    	Address__r.LastModifiedBy.Name, Address__r.LastModifiedDate, LastModifiedBy.Name, LastModifiedDate
											 FROM Contact_Address__c
											 WHERE Contact__c = :contactID AND Primary_Mail_To__c = true];
		if(ctcAddrs.size() == 1) contactAddress = ctcAddrs[0];
		else {contactAddress = null; return;}
		address = contactAddress.Address__r;
		addressSelected = true;
		originalAddress = new Address__c(  Address_Line_1__c = contactAddress.Address__r.Address_Line_1__c
										  , Address_Line_2__c = contactAddress.Address__r.Address_Line_2__c
										  , Address_Line_3__c = contactAddress.Address__r.Address_Line_3__c
										  , Address_Line_4__c = contactAddress.Address__r.Address_Line_4__c
										  , City__c = contactAddress.Address__r.City__c
										  , Country__c =  contactAddress.Address__r.Country__c
										  , State_Province__c = contactAddress.Address__r.State_Province__c
										  , Postal_Code__c = contactAddress.Address__r.Postal_Code__c
										  , Address_Name__c = contactAddress.Address__r.Address_Name__c
									  	  , IE_ID__c = contactAddress.Address__r.IE_ID__c
									  	  , DCW_ID__c = contactAddress.Address__r.DCW_ID__c
									  	  , Warehouse_Id__c = contactAddress.Address__r.Warehouse_Id__c
										  , State_Province_ISO_Code__c = contactAddress.Address__r.State_Province_ISO_Code__c
										  , Country_ISO_Code__c = contactAddress.Address__r.Country_ISO_Code__c
										  , Id = contactAddress.Address__r.Id
										  );


    }

    // Gets all fields used in the page for querying
    public String queryFields{
    	get{
    		if(queryFields == null){
    			queryFields = ''; // Fields not in fieldsets can be added here, separated by commas
    			List<Schema.FieldSetMember> allFieldSets = new List<Schema.FieldSetMember>();
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Contact_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Strategic_Account_Management.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Additional_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.DCW_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.System_Information.getFields());
    			for(Integer i = 0; i < allFieldSets.size(); i++){
    				if(!String.isEmpty(queryFields)) queryFields += ', ';
    				queryFields += allFieldSets[i].getFieldPath();
    			}
    		}
    		return queryFields;
    	}
    	set;
    }
    
    public PageReference selectAddress()
    {
        if(contactAddress.Address__c != null)
        {
            address = [select Address_Line_1__c
                            , Address_Line_2__c
                            , Address_Line_3__c
                            , Address_Line_4__c
                            , City__c
                            , Country__c
                            , State_Province__c
                            , Postal_Code__c
                            , Name
                            , OwnerId 
                            , Address_Name__c
                            , DCW_Id__c
                            , Warehouse_Id__c
                            , IE_ID__c
                            , State_Province_ISO_Code__c
                            , Country_ISO_Code__c
                            , LastModifiedBy.Name
                            , LastModifiedDate
                        from Address__c
                       where Id = :contactAddress.Address__c];
                       
            addressSelected = true;
            contactAddress.Active__c = true;
        }
        else
        {
            addressSelected = false;
            address = new Address__c();
            contactAddress = null;
        }
        
        return null;
    }
    
    public PageReference Save(){
	    PageReference pg;
        Id prevContId = mainContact.Id;
        Contact_Address__c prevContAdd = contactAddress.clone(true, true);
        Address__c prevOrigAdd = originalAddress.clone(true, true);
        Address__c prevAdd = address.clone(true, true);
        Savepoint sp = Database.setSavepoint();
        
         
		    recordSaved = false;
			
            If(mainContact.Id != NULL){
                update mainContact;
                if(addressSelected == false) originalAddress = null;
                if(contactAddress.Contact__c == null) contactAddress.Contact__c = mainContact.Id;
    
                AddressHelper.saveContactAddress(  new List<ContactAddressDetail.ContactAddressWrapper>()
                                                   , new List<ContactAddressDetail.AccountAddressWrapper>()
                                                   , originalAddress
                                                   , address
                                                   , contactAddress
                                                   , addressSelected);
    
                pg= new ApexPages.StandardController(mainContact).view();
                pg.setRedirect(true);
                recordSaved = true;
            
            
            	return redirectPage? pg : null;
            } else{
                Database.DMLOptions dml = new Database.DMLOptions(); 
                dml.DuplicateRuleHeader.allowSave = true;
                dml.DuplicateRuleHeader.runAsCurrentUser = true;
                Database.SaveResult saveResult = Database.insert(mainContact, dml);
                
                system.debug('mainContact is: '+ mainContact);
                system.debug('save result is: '+ saveResult);
                
            	if (!saveResult.isSuccess()) {
                	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                        
                        //duplicateRecords = new List<Contact>();
                        //hasDupResult = False;
                        // Return only match results of matching rules that find duplicate records
                        Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                        System.debug('Match Results: ' + matchResults);
                        // Just grab first match result (which contains the duplicate record found and other match info)
                        Datacloud.MatchResult matchResult = matchResults[0];
                        System.debug('Match Result: ' + matchResult);
                        Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
                        System.debug('matchRecords: ' + matchRecords);
                        // Add matched record to the duplicate records variable
                        for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        duplicateRecords.add((Contact)matchRecord.getRecord());
                        System.Debug('Final Duplicate Records: '+ duplicateRecords);
                    } 
                    this.hasDupResult = TRUE;
                    System.Debug('hasDupResult: '+ this.hasDupResult);
                    System.Debug('Final Duplicate Records: '+ duplicateRecords);
                }
                        
            
            }
            
            
        }
                //If there’s a duplicate record, stay on the page
                return null;
            }

            
    }
    
    public PageReference saveAndNew() {
        PageReference pg =  Page.NewContactPageWithAddress;
        pg.setRedirect(true);
        return save() == null ? null : pg;
    }
}

Please see the highlighted code which needs to rerender the page block in Visualforce component id = DupRecords.

Thanks for your help.
  • January 24, 2017
  • Like
  • 0