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
Lakshya KanchanLakshya Kanchan 

Activate/Deactivate duplicate rules using apex or, SFDX CLI

Hi

I have to automate certain manual checking steps done in the Salesforce org.

e.g. checking whether Account object has a record type with a specific API name or, not.

For that I am making use of SFDX CLI & apex code (run using SFDX CLI) to automate the items.

My business requirement is to activate/deactivate duplicate rules using apex or, through any command of SFDX CLI.

I want your help/suggestions on how to perform it.

Regards,
Lakshya
SwethaSwetha (Salesforce Developers) 
HI Lakshya,

To activate or deactivate Duplicate Rules using Apex, you can use the Metadata API.
 
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();

MetadataService.DuplicateRule duplicateRule = new MetadataService.DuplicateRule();
duplicateRule.fullName = 'My_Duplicate_Rule';

MetadataService.DuplicateRule[] duplicateRules = new MetadataService.DuplicateRule[] {duplicateRule};

MetadataService.UpsertResult[] results = service.updateMetadata(new MetadataService.Metadata[] {new MetadataService.Metadata {fullName = 'My_Duplicate_Rule', type_x = 'DuplicateRule', isActive = false}});

if (results[0].success) {
    System.debug('Duplicate Rule deactivated successfully.');
} else {
    System.debug('Error deactivating Duplicate Rule: ' + results[0].errors[0].message);
}

Update the "My_Duplicate_Rule" in code with your actual duplicate rule name
Related: https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_duplicaterule.htm

To activate or deactivate Duplicate Rules using the SFDX CLI,try
sfdx force:data:record:update -s DuplicateRule -w "DeveloperName='My_Duplicate_Rule'" -v "IsActive=false"

If this information helps, please mark the answer as best. Thank you
Lakshya KanchanLakshya Kanchan
Hi Swetha,

Thanks for the quick response.

The SFDX CLI approach didnt work.

We are going with the MetadataService class approach for now.