How to prevent duplicate record using trigger?

on

|

views

and

comments

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 Singhhttps://www.pantherschools.com/
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
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; itโ€™s the cornerstone of development on the Salesforce Platform. Itโ€™s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential