Real-time Duplicate Checking in Salesforce LWC: A Developer's Guide

Intoduction

When working with Lightning Web Components and Apex to create records in Salesforce, managing duplicates is essential for data quality. This blog post provides a comprehensive guide to implementing duplicate rule handling in this context. We'll cover Matching Rule and Duplicate Rule setup and how to integrate them with your Apex controllers for seamless LWC integration.

Steps to Create Matching Rules and Duplicate Rules

Step 1: Creating a Matching Rule

  1. Navigate to Setup.

  2. In the Quick Find box, search for Matching Rules.

  3. Click New Rule and select the object (e.g., Contact).

  4. Define the matching criteria (e.g., Email, Phone, or First Name & Last Name combination).

    Step 2: Creating a Duplicate Rule

    1. Navigate to Setup.

    2. In the Quick Find box, search for Duplicate Rules.

    3. Click New Rule and select the object (e.g., Contact).

    4. Define the rule name and matching rule (created in Step 1).

    5. Choose the action to take when a duplicate is found (e.g., Block or Allow and Alert User).

    6. Click Save and then Activate the Duplicate Rule.

Implementing Duplicate Rule Handling in Apex

Below is an Apex controller that handles duplicate checking while inserting contacts.

public with sharing class ContactController {
    @AuraEnabled
    public static String createContact(Contact con, Boolean bypassRules) {
        try {
            // Create DML options to configure duplicate rule behavior
            Database.DmlOptions dmlOptions = new Database.DmlOptions();
            dmlOptions.DuplicateRuleHeader.runAsCurrentUser = true; // Runs duplicate rules as the current user

            // Determine whether to bypass the duplicate rules
            if (!bypassRules) {
                dmlOptions.DuplicateRuleHeader.allowSave = false; // Prevents duplicate record insertion
            } else {
                dmlOptions.DuplicateRuleHeader.allowSave = true; // Allows duplicate record insertion
            }

            // Apply DML options to the contact record
            con.setOptions(dmlOptions);

            // Attempt to insert the contact record
            Database.SaveResult result = Database.insert(con, dmlOptions);

            // Check if the insert operation was successful
            if (result.isSuccess()) {
                return 'Success';
            } else {
                return result.getErrors()[0].getMessage(); // Return duplicate rule error
            }
        } catch (Exception e) {
            return e.getMessage(); // Return any unexpected exception message
        }
    }
}

Implementing the LWC

Now, let's create a Lightning Web Component (LWC) that calls the Apex method and handles duplicate rule alerts.

<template>
    <lightning-card title="Create Contact">
        <div class="slds-m-around_medium">
            <lightning-input label="First Name" value={firstName} onchange={handleChange} data-field="FirstName"></lightning-input>
            <lightning-input label="Last Name" value={lastName} onchange={handleChange} data-field="LastName"></lightning-input>
            <lightning-input label="Email" value={email} onchange={handleChange} data-field="Email"></lightning-input>
            <lightning-button label="Create Contact" onclick={createContact}></lightning-button>
        </div>
    </lightning-card>
</template>
import { LightningElement, track } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ContactForm extends LightningElement {
    @track firstName;
    @track lastName;
    @track email;

    // Handle input field changes and update component properties
    handleChange(event) {
        this[event.target.dataset.field] = event.target.value;
    }

    // Function to create a contact record
    createContact() {
        let contact = {
            FirstName: this.firstName,
            LastName: this.lastName,
            Email: this.email
        };

        // Call Apex method to create contact
        createContact({ con: contact, bypassRules: false })
            .then(result => {
                if (result === 'Success') {
                    this.showToast('Success', 'Contact created successfully!', 'success');
                } else {
                    this.showToast('Duplicate Found', result, 'warning');
                    // Prompt the user to override duplicate rule
                    if (confirm('A duplicate record exists. Do you want to proceed?')) {
                        createContact({ con: contact, bypassRules: true })
                            .then(res => this.showToast('Success', 'Duplicate contact created!', 'success'))
                            .catch(error => this.showToast('Error', error.body.message, 'error'));
                    }
                }
            })
            .catch(error => {
                this.showToast('Error', error.body.message, 'error');
            });
    }

    // Function to display toast messages
    showToast(title, message, variant) {
        this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
    }
}

Conclusion

Preventing duplicate records during LWC inserts is a critical aspect of maintaining data quality in Salesforce. By using Apex to enforce Duplicate Rules, you can ensure that your data remains clean and consistent. Start implementing these techniques today to improve your data integrity and streamline your data entry processes.