Find duplicate records

This post will help you find the duplicate record Id in apex before creating a record in salesforce.

Standard salesforce feature will always warn you about the duplicate record error, when you try to create a contact, lead and account using the standard way. What if you want to check for the duplicate record from a custom lightning form or through integration.

CheckDuplicateRecord method in CreateLeadController class will return the duplicate record ids. After getting the duplicate record ID you can take appropriate steps to further use of this duplicate id based on your requirement.

Go through the below steps to implement the scenario.


Step 1 : Activate duplicate rule on Lead.

Step 2 : Create a lightning form to create lead in salesforce and create a controller to check for duplicate record.

LeadFormComponent.cmp

<aura:component controller="CreateLeadController" 
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,
                            force:hasRecordId,forceCommunity:availableForAllPageTypes" 
                access="global" >



    <!-- Define Attribute-->
    <aura:attribute name="lead" type="Lead" default="{'sobjectType': 'Lead',
                         'FirstName': '',
                         'LastName': '',
                         'Company': '', 
                         'Email': '',
                         'Phone': ''                            
                       }"/>
    <div class="slds-card">
        <h3>Please Enter The Lead Information</h3>
        <div >
            <label>First Name</label>
            <ui:inputText class="form-control" value="{!v.lead.FirstName}"/>
        </div>
        <div >
            <label>Last Name</label>
            <ui:inputText class="form-control" value="{!v.lead.LastName}"/>
        </div>
        <div >
            <label>Email Address</label>
            <ui:inputText class="form-control" value="{!v.lead.Email}"/>
        </div>
        <div >
            <label>Phone</label>
            <ui:inputText class="form-control" value="{!v.lead.Phone}"/>
        </div>
         <div >
            <label>Company</label>
            <ui:inputText class="form-control" value="{!v.lead.Company}"/>
        </div>
    </div>
    <div>
        <ui:button class="btn btn-default" press="{!c.create}">Create Lead</ui:button>
  </div>
</aura:component>
LeadFormComponentController.js

({
    create : function(component, event, helper) {
        console.log('Create record');

        //getting the candidate information
        var record = component.get("v.lead");

        //Validation
        if($A.util.isEmpty(record.FirstName) || $A.util.isUndefined(record.FirstName)){
            alert('First Name is Required');
            return;
        }            
        if($A.util.isEmpty(record.LastName) || $A.util.isUndefined(record.LastName)){
            alert('Last Name is Required');
            return;
        }
        if($A.util.isEmpty(record.Email) || $A.util.isUndefined(record.Email)){
            alert('Email is Required');
            return;
        }
        if($A.util.isEmpty(record.Company) || $A.util.isUndefined(record.Company)){
            alert('Company is Required');
            return;
        }
        if($A.util.isEmpty(record.Phone) || $A.util.isUndefined(record.Phone)){
            alert('Phone is Required');
            return;
        }
        //Calling the Apex Function
        var action = component.get("c.createRecord");

        //Setting the Apex Parameter
        action.setParams({
            leadRec : record
        });

        //Setting the Callback
        action.setCallback(this,function(response){
            //get the response state
            var state = response.getState();

            //check if result is successfull
            if(state == "SUCCESS"){
                //Reset Form
                console.log(response.getReturnValue());
                if(!response.getReturnValue().isError){
                    if(response.getReturnValue().isDuplicate){
                         alert('Lead Record is duplicate with following records'+ response.getReturnValue().duplicateRecordId);
                    }else{
                        alert('Record Created Succesfully');
                    }
                }else{
                    alert(response.getReturnValue().errorMessage);
                }

            } else if(state == "ERROR"){
                alert('Error in calling server side action');
            }
        });

        //adds the server-side action to the queue        
        $A.enqueueAction(action);

    }
})


CreateLeadController


public class CreateLeadController {
    @AuraEnabled
    public static ResponseWrapper createRecord (Lead leadRec){

        List<Lead> leadList = new List<Lead>();
        ResponseWrapper wrap = new ResponseWrapper();
        try{
            leadList.add(leadRec);
            wrap = checkDuplicateRecord(leadList);  
            if(wrap.isDuplicate){
                return wrap;
            }else{
                insert leadList;
                wrap.isError= false;
                return wrap;
            }

        } catch (Exception ex){
            wrap.isError = true;
            wrap.errorMessage = ex.getMessage();
            return wrap;
        }

    }   
    /*
     * Check for Duplicate record in salesforce and return duplicate recordIds.

     * */
    public static ResponseWrapper checkDuplicateRecord(List<Sobject> recList){
        Datacloud.FindDuplicatesResult[] results = Datacloud.FindDuplicates.findDuplicates(recList);
        Boolean foundDuplicate = false;
         List<id> matchRecordsId = new List<id>();
        for (Datacloud.FindDuplicatesResult findDupeResult : results) {
            for (Datacloud.DuplicateResult dupeResult : findDupeResult.getDuplicateResults()) {
                for (Datacloud.MatchResult matchResult : dupeResult.getMatchResults()) {
                    for (Datacloud.MatchRecord matchRecord : matchResult.getMatchRecords()) {
                        foundDuplicate = true;
                        //System.debug(matchRecord.getRecord().);
                        matchRecordsId.add(matchRecord.getRecord().Id);

                    }
                }
            }
        }
        ResponseWrapper  wrap = new ResponseWrapper();
        if(foundDuplicate){
            wrap.isDuplicate = true;
            wrap.duplicateRecordId = String.valueOf(matchRecordsId);
        }else{
            wrap.isDuplicate = false;
            wrap.duplicateRecordId = '';
        }
        return wrap;
    }


    public class ResponseWrapper{
        @auraEnabled
        public Boolean isDuplicate{get;set;}
        @auraEnabled
        public String duplicateRecordId{get;set;}
        @auraEnabled
        public Boolean isError{get;set;}
        @auraEnabled
        public String errorMessage{get;set;}

    }
}





Comments

Popular posts from this blog

Send LWC as PDF attachment in an Email

Multi Select Look Up Using LWC

Draw Chart in LWC using chart.js