How to prevent duplicate record using trigger?

Table of Contents

Introduction to Scenario

The business got to know that there are multiple accounts with the same name and rating. Now, as a developer, you need to make sure that no new duplicates are being created with the same name and rating.

Questions?

  • Which Object?
    • Account
  • Which Event?
    • before insert
    • before update
  • The problem that we are solving?
    • The business got to know that there are multiple accounts with the same name and rating. Now, as a developer, you need to make sure that no new duplicates are being created with the same name and rating.

Helper Class

				
					public class AccountTriggerHelper {
    // reusable methods - focus
    // further processing
    // 
    public static void updateAccountShippingAddress(List<Account> accountList){
        /*
            Develop an Apex Trigger so that every time 
            1. when any account is inserted then set the value of the Industry field to Education.
            Also, 
            2. check if the Description is black then set
            the value for the description to “Account Description was blank”
        */
        // sObject
        //         Standard
        //         Custom
        //List<Account> accountList = Trigger.New; // List<sObject>
        for(Account acc : accountList){ //List<sObject>
            if(acc.Industry == null){
                acc.Description = 'Account Industry was blank';   
            }
            /* 
                Develop an Apex Trigger so that every time when any account 
                is created or updated then 
                Set the Value of the Billing Address is to Shipping Address.
                ShippingStreet
                ShippingCity
                ShippingState
                ShippingPostalCode
                ShippingCountry
            */
            if(acc.ShippingStreet == null ){
            }else if(acc.ShippingCity == null){
            }else if(acc.ShippingCountry == null){
            }
            System.debug(acc.ShippingAddress);
            if(acc.ShippingAddress == null){
                system.debug('ShippingAddress is null ');
            }
            //  acc.ShippingStreet == null => True
            if(acc.ShippingStreet == null || acc.ShippingCity == null || acc.ShippingState == null || acc.ShippingPostalCode == null || acc.ShippingCountry == null){
                acc.ShippingStreet         = acc.BillingStreet; // data type must be same
                acc.ShippingCity         = acc.BillingCity;
                acc.ShippingState         = acc.BillingState;
                acc.ShippingPostalCode  = acc.BillingPostalCode;
                acc.ShippingCountry     = acc.BillingCountry;
            }
        }
    }
    public static void checkDuplicateAccount(List<Account> newRecords){
        /*
         * The business got to know that there are multiple accounts with the same name and rating.
           Now, as a developer, you need to make sure that no new duplicates are being
           created with the same name and rating. 
        */
        Set<String> accountNameSet = new Set<String>();
        Set<String> accountRatingSet = new Set<String>();
        // newRecords - 2
        // Demo - Name
        // Hot - Rating
        // (Demo, Demo)
        // (Rating, Rating)
        // {Demo}
        // {Rating}
        for(Account acc : newRecords){
            accountNameSet.add(acc.Name);
            accountRatingSet.add(acc.Rating);
        }
        List<Account> existingAccountList = [SELECT Id, Name, Rating 
                                             FROM Account
                                             WHERE Name IN: accountNameSet
                                             AND Rating IN: accountRatingSet
                                             AND Id NOT IN :newRecords
                                             LIMIT 50000
                                           ];
        for(Account acc : newRecords){ //Trigger.New
            for(Account extAcc: existingAccountList){
                if(acc.Name == extAcc.Name && acc.Rating == extAcc.Rating){
                    acc.addError('Duplicate account already exists with same name and rating!');
                    acc.Name.addError('Duplicate account already exists with same name and rating!');
                    acc.Rating.addError('Duplicate account already exists with same name and rating!');
                }
            }
        }
    }
}
				
			

Apex Scenario

Develop a Solution on Opportunity so that if the StageName of the Opportunity is already set to “Closed Won” and now if any user is trying to Change the Amount or Account of the Opportunity the user should get the Error.

Note: – You need to utilize the Apex Trigger to achieve this functionality

Dispatcher Class

				
					public class OpportunityTriggerDispatcher {
    public static void dispatch(System.TriggerOperation operationType){
        switch on operationType{
            WHEN BEFORE_INSERT{
                OpportunityTriggerHandler.handleBeforeInsert(Trigger.New);
            }
            WHEN BEFORE_UPDATE{
                OpportunityTriggerHandler.handleBeforeUpdate(Trigger.New, (Map<Id, Opportunity>)Trigger.oldMap);
            }
        }
    }
}
				
			

Handler Class

				
					public class OpportunityTriggerHandler {
    /*
        Develop an Apex Trigger on Opportunity so that 
        if the Discount & Amount field is not blank then calculate the discount 
        and store it in the Discount Price field.
        To Calculate the discount use the below formula and store it in a variable
        Decimal discount = ( Discount * Amount ) / 100
        To Calculate the Discounted Price use the below calculation and store it in a variable 
        Decimal discountedAmount = Amount - discount;
    */
    public static void handleBeforeInsert(List<Opportunity> opportunityList){
        for(Opportunity opp : opportunityList){
            if(opp.Amount != null && opp.Discount__c != null){
                Decimal discount = ( opp.Amount * opp.Discount__c ) / 100;
                Decimal discountedAmount = opp.Amount - discount;
                opp.Discounted_Price__c = discount;
                opp.Price_After_Discount__c  = discountedAmount;
            }
        }
    }
    // Triggger.oldMap - Map<Id, sObject> ~= Map<Id, Opportunity>
    // Opportunity Id - Opportunity (Old Version) - Amount , StageName
    public static void handleBeforeUpdate(List<Opportunity> newRecords, Map<Id, Opportunity> oldRecordMap){
        for(Opportunity newRecord: newRecords){
            Opportunity oldRecord = oldRecordMap.get(newRecord.Id);
            if(oldRecord.StageName == 'Closed Won' && newRecord.StageName == 'Closed Won' &&  oldRecord.Amount <> newRecord.Amount){
                newRecord.Amount.addError('Amount Can not be changed once the Stage is Set to Closed Won');
            }
            if(oldRecord.StageName == 'Closed Won' && newRecord.StageName == 'Closed Won' &&  oldRecord.Discount__c <> newRecord.Discount__c){
                newRecord.Discount__c.addError('Discount Can not be changed once the Stage is Set to Closed Won');
            }
        }
    }
}
				
			

Watch Complete Video

Assignments

→ Apex Trigger 6

Prerequisite

  • Create a Custom Object and Name it “Location”. Relate this location object with Account using Lookup relationship.
  • Create a field on Account “Number of Locations” of type Number

Develop a solution that will create the location records when the Account is created and the “Number of Locations” field has some value in it. The no of locations related to the account should be the same as the value in the “Number of Locations” field.

For Example – if the value of the “Number of Locations” field is 4 then there should be 4 location records created under that account.

→ Apex Trigger 7
Develop an Apex Trigger to prevent the duplicate Contact record using Name & Email. So if there are duplicate records with the same Name & Email new Record should not get created.

→ Apex Trigger 8
Develop an Apex Trigger to prevent Duplicate Leads if there is already an existing Lead record with the same Email & Company.

Resources

Amit Singh
Amit Singh

Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion

Articles: 299

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from Panther Schools

Subscribe now to keep reading and get access to the full archive.

Continue reading