Newer Version Available

This content describes an older version of this product. View Latest

DuplicateResult Class

Represents the details of a duplicate rule that detected duplicate records and information about those duplicate records.

Namespace

Datacloud

Usage

The DuplicateResult class and its methods are available to organizations that use duplicate rules.

DuplicateResult is contained within DuplicateError, which is part of SaveResult. SaveResult is generated when a user attempts to save a record in Salesforce.

Example

This example shows a custom application that lets users add a contact. When a contact is saved, an alert displays if there are duplicate records.

The sample application consists of a Visualforce page and an Apex controller. The Visualforce page is listed first so that you can see how the page makes use of the Apex controller. Save the Apex class first before saving the Visualforce page.

1<apex:page controller="ContactDedupeController">
2    <apex:form >
3        <apex:pageBlock title="Duplicate Records" rendered="{!hasDuplicateResult}">
4            <apex:pageMessages />
5            <apex:pageBlockTable value="{!duplicateRecords}" var="item">
6                <apex:column >
7                    <apex:facet name="header">Name</apex:facet>
8                    <apex:outputLink value="/{!item['Id']}">{!item['Name']}</apex:outputLink>
9                </apex:column>
10                <apex:column >
11                    <apex:facet name="header">Owner</apex:facet>
12                    <apex:outputField value="{!item['OwnerId']}"/>
13                </apex:column>
14                <apex:column >
15                    <apex:facet name="header">Last Modified Date</apex:facet>
16                    <apex:outputField value="{!item['LastModifiedDate']}"/>
17                </apex:column>
18            </apex:pageBlockTable> 
19        </apex:pageBlock>
20        
21        <apex:pageBlock title="Contact" mode="edit">
22            <apex:pageBlockButtons >
23                <apex:commandButton value="Save" action="{!save}"/>
24            </apex:pageBlockButtons>         
25
26            <apex:pageBlockSection >
27                <apex:inputField value="{!Contact.FirstName}"/>
28                <apex:inputField value="{!Contact.LastName}"/>
29                <apex:inputField value="{!Contact.Email}"/>
30                <apex:inputField value="{!Contact.Phone}"/>
31                <apex:inputField value="{!Contact.AccountId}"/>
32            </apex:pageBlockSection>
33        </apex:pageBlock>
34    </apex:form>
35</apex:page>

This sample is the Apex controller for the page. This controller contains the action method for the Save button. The save method inserts the new contact. If errors are returned, this method iterates through each error, checks if it’s a duplicate error, adds the error message to the page, and returns information about the duplicate records to be displayed on the page.

1public class ContactDedupeController {
2    
3    // Initialize a variable to hold the contact record you're processing
4    private final Contact contact;
5    
6    // Initialize a list to hold any duplicate records
7    private List<sObject> duplicateRecords;
8    
9    // Define variable that’s true if there are duplicate records
10    public boolean hasDuplicateResult{get;set;}
11    
12    // Define the constructor
13    public ContactDedupeController() {
14        
15        // Define the values for the contact you’re processing based on its ID
16        Id id = ApexPages.currentPage().getParameters().get('id');
17        this.contact = (id == null) ? new Contact() : 
18            [SELECT Id, FirstName, LastName, Email, Phone, AccountId 
19             FROM Contact WHERE Id = :id];
20       
21        // Initialize empty list of potential duplicate records
22        this.duplicateRecords = new List<sObject>();
23        this.hasDuplicateResult = false;
24    }
25    
26    // Return contact and its values to the Visualforce page for display
27    public Contact getContact() {
28        return this.contact;
29    }
30    
31    // Return duplicate records to the Visualforce page for display
32    public List<sObject> getDuplicateRecords() {
33        return this.duplicateRecords;
34    }
35    
36    // Process the saved record and handle any duplicates
37    public PageReference save() {
38        
39        // Optionally, set DML options here, use “DML” instead of “false” 
40        //   in the insert()
41        // Database.DMLOptions dml = new Database.DMLOptions(); 
42        // dml.DuplicateRuleHeader.allowSave = true;
43        // dml.DuplicateRuleHeader.includeRecordDetails = true;
44        // dml.DuplicateRuleHeader.runsAsCurrentUser = true;
45        Database.SaveResult saveResult = Database.insert(contact, false);
46
47        if (!saveResult.isSuccess()) {
48            for (Database.Error error : saveResult.getErrors()) {
49                // If there are duplicates, an error occurs
50                // Process only duplicates and not other errors 
51                //   (e.g., validation errors)
52                if (error instanceof Database.DuplicateError) {
53                    // Handle the duplicate error by first casting it as a 
54                    //   DuplicateError class
55                    // This lets you use methods of that class 
56                    //  (e.g., getDuplicateResult())
57                    Database.DuplicateError duplicateError = 
58                            (Database.DuplicateError)error;
59                    Datacloud.DuplicateResult duplicateResult = 
60                            duplicateError.getDuplicateResult();
61                    
62                    // Display duplicate error message as defined in the duplicate rule
63                    ApexPages.Message errorMessage = new ApexPages.Message(
64                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
65                            duplicateResult.getErrorMessage());
66                    ApexPages.addMessage(errorMessage);
67                    
68                    // Get duplicate records
69                    this.duplicateRecords = new List<sObject>();
70
71                    // Return only match results of matching rules that 
72                    //  find duplicate records
73                    Datacloud.MatchResult[] matchResults = 
74                            duplicateResult.getMatchResults();
75
76                    // Just grab first match result (which contains the 
77                    //   duplicate record found and other match info)
78                    Datacloud.MatchResult matchResult = matchResults[0];
79
80                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
81
82                    // Add matched record to the duplicate records variable
83                    for (Datacloud.MatchRecord matchRecord : matchRecords) {
84                        System.debug('MatchRecord: ' + matchRecord.getRecord());
85                        this.duplicateRecords.add(matchRecord.getRecord());
86                    }
87                    this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
88                }
89            }
90            
91            //If there’s a duplicate record, stay on the page
92            return null;
93        }
94        
95        //  After save, navigate to the view page:
96        return (new ApexPages.StandardController(contact)).view();
97    }
98    
99}

DuplicateResult Methods

The following are methods for DuplicateResult.

getDuplicateRule()

Returns the developer name of the executed duplicate rule that returned duplicate records.

Signature

public String getDuplicateRule()

Return Value

Type: String

getErrorMessage()

Returns the error message configured by the administrator to warn users they may be creating duplicate records. This message is associated with a duplicate rule.

Signature

public String getErrorMessage()

Return Value

Type: String

Example

This example shows the code used to display the error message when duplicates are found while saving a new contact. This code is part of a custom application that lets users add a contact. When a contact is saved, an alert displays if there are duplicate records. Review DuplicateResult Class to check out the entire sample applicaton.

1ApexPages.Message errorMessage = new ApexPages.Message(
2                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
3                            duplicateResult.getErrorMessage());
4                    ApexPages.addMessage(errorMessage);

getMatchResults()

Returns the duplicate records and match information.

Signature

public List<Datacloud.MatchResult> getMatchResults()

Return Value

Type: List<Datacloud.MatchResult>

Example

This example shows the code used to return duplicate record and match information and assign it to the matchResults variable. This code is part of a custom application that implements duplicate management when users add a contact. See DuplicateResult Class to check out the entire sample applicaton.

1Datacloud.MatchResult[] matchResults = 
2                            duplicateResult.getMatchResults();

isAllowSave()

Indicates whether the duplicate rule will allow a record that’s identified as a duplicate to be saved. Set to true if duplicate rule should allow save; otherwise, false.

Signature

public Boolean isAllowSave()

Return Value

Type: Boolean