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
Sainath VenkatSainath Venkat 

Trigger to check check box on account for insert and update

Hello guys

I am having one scenario, while creating contact, I will be checking the email id of contact and if duplicate email id found for specific account it relates then I have a Checkbox__c field on account and it should be unchecked.
by default Vheckbox__c will be checked.
While creating contact for a particular account,if email is already found on that particular account then checkbox should be unchecked
Lets Say I have account A1 and have Checkbox__c field checked by default.
Now I will add contacts for the account A1. I am adding first contact C1 with email xyz@gmail.com and I will add another contact C2 with same email id xyz@gmail.com, since two contacts have same email id then Checkbox__c should get unchecked and I will update contact C2 with email abc@gmail.com and now two contacs have different email ids the Checkbox__c should get checked.

If I get any help then it will be really helpful.
Best Answer chosen by Sainath Venkat
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Sainath,

I think you can write an After Insert/update trigger on this :

Trigger on Contact:
trigger ContactTrigger on Contact (before insert,before update,after insert,after update) {
    
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            UpdateAccountOnContact.UpdateAccountOnContactMethod(trigger.newMap);
        }
        if(trigger.isUpdate)
        {
            UpdateAccountOnContact.UpdateAccountOnContactMethod(trigger.newMap);
        }
    }
}



Class for the trigger can be as follows:
public class UpdateAccountOnContact {
    public static void UpdateAccountOnContactMethod(Map<id,Contact> newContactMap)
    {
        Set<Id> uncheckaccId=new Set<Id>();
        Set<Id> checkaccId=new Set<Id>();
        Set<Id> accId=new Set<Id>();
        Set<String> Email =new Set<String>();
        for(Contact c:newContactMap.values())
        {
           accId.add(c.AccountId); 
        }
        List<Contact> conList=[select id,email,AccountId from Contact where AccountId in: accId ];
        system.debug(conList);
        for(Contact con:conList)
        {
            if(newContactMap.containsKey(con.Id))
            {
                if(Email.contains(newContactMap.get(con.Id).email))
                {
                    uncheckaccId.add(newContactMap.get(con.Id).AccountId); 
                    checkaccId.remove(newContactMap.get(con.Id).AccountId);
                    
                }
                else
                {
                    Email.add(newContactMap.get(con.Id).email);
                    checkaccId.add(newContactMap.get(con.Id).AccountId);
                }   
            }
            else
            {
                if(Email.contains(con.email))
                {
                    uncheckaccId.add(con.AccountId); 
                    checkaccId.remove(con.AccountId);
                    
                }
                else
                {
                    Email.add(con.email);
                    checkaccId.add(con.AccountId);
                }
                
            }
            
        }
        system.debug('checkaccId'+checkaccId);
        system.debug('uncheckaccId'+uncheckaccId);
        List<Account> accList=[select id,checkBox__c from Account where id in: uncheckaccId or id in: checkaccId];
        for(Account a: accList)
        {
            if(uncheckaccId.contains(a.id))
            {
                 a.checkBox__c=false;
            }
                
            if(checkaccId.contains(a.Id) && a.checkBox__c!=true)
            {
                a.checkBox__c=true;
                
            }
                
        }
        system.debug(accList);
        update accList;
        
        
    }
    
}

This worked for me for your requirement.Please check and let me know if any queries.

Thanks
Bhargavi.

All Answers

Jainam ContractorJainam Contractor
Hi Sai,

You can accomplish this using APEX Trigger.

You can write trigger on Contact object for after Insert and after Update event.

When a Contact is added, create a map of Account Id and all the related Contact Email id for that particular account.

Then iterate over the list of the new Contacts and check if Email exists in that particular Contact Email list of Map. If Email exists then Check the Checkbox__c field on that particular account field.

Let me know if it works or you need anymore help.

Thanks,
Jainam Contractor,
Salesforce Developer,
Varasi LLC
Sainath VenkatSainath Venkat
Hi Jainam,

Actually I have written Handler class and I am calling that class into trigger and it's working on creation but its not working on update

if possible,can you please help me out with code.
I am attaching my Handler class here.
public with sharing class DuplicateContactValidationsHandler {
    public static void validateEmailPhoneFields (List<Contact> lstContact) {
        Set<String> setEmailValues = new Set<String>();
        List<String> lstEmailValues = new List<String>();
		List<Id> lstContactIds = new List<Id>();
		List<Account> lstAccountsToUpdate = new List<Account>();

        for(Contact contactObj : lstContact) {
            lstEmailValues.add(contactObj.Email);
        }

        for(Contact contactObj : [SELECT Email
                                    FROM Contact
                                   WHERE Email IN :lstEmailValues]) {
            setEmailValues.add(contactObj.Email);
        }

        for(Contact contactObj : lstContact ) {
            if(contactObj.Email != null ) {
                if(setEmailValues.contains(contactObj.Email) ) {
                   lstContactIds.add(contactObj.AccountId);
                }
            }
        }
		
		for(Account accountInstance : [SELECT AllContactsUniqueEmail__c FROM ACCOUNT WHERE Id IN : lstContactIds]) {
			accountInstance.AllContactsUniqueEmail__c = False;
			lstAccountsToUpdate.add(accountInstance);
		}
		if(lstAccountsToUpdate.size() > 0) {
			update lstAccountsToUpdate;
		}
    }
}

 
Jainam ContractorJainam Contractor
Hi Sai,

Can you share your Trigger code..???

Thanks
Sainath VenkatSainath Venkat
Jainam,
the trigger that I have written is as follows
trigger PreventDuplicateContactAndCount on Contact (before insert, before update, after insert, after update, after delete) {


    if(trigger.isBefore) {
       if(Trigger.isUpdate || Trigger.isInsert) {
            DuplicateContactValidationsHandler.validateEmailPhoneFields(Trigger.new);
        }
    } 
	
	if (trigger.isAfter) {
		Set <Id> accountIds = new Set <Id>();
		List <Account> lstAccountsToUpdate = new List <Account>();
		if(Trigger.isInsert){
			for(Contact con:trigger.new) {
				accountIds.add(con.accountID);
			}
		}
		if(Trigger.isUpdate|| Trigger.isDelete){
			for(Contact con:trigger.old){
				accountIds.add(con.accountID);
			}
		}

		for(Account acc:[SELECT Id,Name,Number_Of_Contacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
			Account accObj = new Account ();
			accObj.Id = acc.Id;
			accObj.Number_Of_Contacts__c= acc.Contacts.size();
			lstAccountsToUpdate.add(accObj);
		}

		update lstAccountsToUpdate;
	}
}

 
Sainath VenkatSainath Venkat
in trigger I have two things, one is I need to check duplicate email of contact for a particular account basing on that checkbox__c will be checked or unchecked and one more is I need to count the number of contacts for a particular account.
Jainam ContractorJainam Contractor
Hi Sai,

For me its working in both the cases. Insert as well as Update.

What is not working for you in Update scenario.

When you update the Contact Email to unique one after changing from Duplicate, it won't check the checkbox again as that logic does not reside in the handler class.

But when you update a Contact and change the Email to some duplicate email id then the Checkbox on the Account will be unchecked if it was checked earlier.

If you also want to check the field then make the below addition to the handler class.
 
public with sharing class DuplicateContactValidationsHandler {
    public static void validateEmailPhoneFields (List<Contact> lstContact) {
        Set<String> setEmailValues = new Set<String>();
        List<String> lstEmailValues = new List<String>();
        List<Id> lstContactIds = new List<Id>();
        Set<Id> setAccountIds = new Set<Id>();
        List<Account> lstAccountsToUpdate = new List<Account>();

        for(Contact contactObj : lstContact) {
            lstEmailValues.add(contactObj.Email);
        }

        for(Contact contactObj : [SELECT Email
                                    FROM Contact
                                   WHERE Email IN :lstEmailValues]) {
            setEmailValues.add(contactObj.Email);
        }

        for(Contact contactObj : lstContact ) {
            if(contactObj.Email != null ) {
                if(setEmailValues.contains(contactObj.Email) ) {
                   lstContactIds.add(contactObj.AccountId);
                }else{
                   setAccountIds.add(contactObj.AccountId); 
                }
            }
        }
        if(lstContactIds != NULL && lstContactIds.size()>0){
            for(Account accountInstance : [SELECT AllContactsUniqueEmail__c FROM ACCOUNT WHERE Id IN : lstContactIds]) {
                accountInstance.AllContactsUniqueEmail__c = False;
                lstAccountsToUpdate.add(accountInstance);
            }
        }
        if(setAccountIds != NULL && setAccountIds.size()>0){
            for(Account accountInstance : [SELECT AllContactsUniqueEmail__c FROM ACCOUNT WHERE Id IN : setAccountIds]) {
                accountInstance.AllContactsUniqueEmail__c = True;
                lstAccountsToUpdate.add(accountInstance);
            }
        }
        if(lstAccountsToUpdate.size() > 0) {
            update lstAccountsToUpdate;
        }
    }
}

Please let me know if it works or you need more help.

Mark as the best solution if it solved your purpose.

Thanks,
Jainam Contractor,
Salesforce Consultant,
Varasi LLC
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Sainath,

I think you can write an After Insert/update trigger on this :

Trigger on Contact:
trigger ContactTrigger on Contact (before insert,before update,after insert,after update) {
    
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            UpdateAccountOnContact.UpdateAccountOnContactMethod(trigger.newMap);
        }
        if(trigger.isUpdate)
        {
            UpdateAccountOnContact.UpdateAccountOnContactMethod(trigger.newMap);
        }
    }
}



Class for the trigger can be as follows:
public class UpdateAccountOnContact {
    public static void UpdateAccountOnContactMethod(Map<id,Contact> newContactMap)
    {
        Set<Id> uncheckaccId=new Set<Id>();
        Set<Id> checkaccId=new Set<Id>();
        Set<Id> accId=new Set<Id>();
        Set<String> Email =new Set<String>();
        for(Contact c:newContactMap.values())
        {
           accId.add(c.AccountId); 
        }
        List<Contact> conList=[select id,email,AccountId from Contact where AccountId in: accId ];
        system.debug(conList);
        for(Contact con:conList)
        {
            if(newContactMap.containsKey(con.Id))
            {
                if(Email.contains(newContactMap.get(con.Id).email))
                {
                    uncheckaccId.add(newContactMap.get(con.Id).AccountId); 
                    checkaccId.remove(newContactMap.get(con.Id).AccountId);
                    
                }
                else
                {
                    Email.add(newContactMap.get(con.Id).email);
                    checkaccId.add(newContactMap.get(con.Id).AccountId);
                }   
            }
            else
            {
                if(Email.contains(con.email))
                {
                    uncheckaccId.add(con.AccountId); 
                    checkaccId.remove(con.AccountId);
                    
                }
                else
                {
                    Email.add(con.email);
                    checkaccId.add(con.AccountId);
                }
                
            }
            
        }
        system.debug('checkaccId'+checkaccId);
        system.debug('uncheckaccId'+uncheckaccId);
        List<Account> accList=[select id,checkBox__c from Account where id in: uncheckaccId or id in: checkaccId];
        for(Account a: accList)
        {
            if(uncheckaccId.contains(a.id))
            {
                 a.checkBox__c=false;
            }
                
            if(checkaccId.contains(a.Id) && a.checkBox__c!=true)
            {
                a.checkBox__c=true;
                
            }
                
        }
        system.debug(accList);
        update accList;
        
        
    }
    
}

This worked for me for your requirement.Please check and let me know if any queries.

Thanks
Bhargavi.
This was selected as the best answer
AshishkAshishk
Write a trigger on contact after insert and update like this.

list emailids, accountids, contactid;

contactids=trigger.newMap.keyset();

for(contact c:trigger.new){
    accountids.add(c.accountid);
    emailids.add(c.emailids);
}



List<Account> lstAcc=[Select id, checkbox,(select id from contacts where email in :emailids and id not in: contactids) from account where id in :accountids and checkbox=true]


if(!lstAcc.isEmpty()){
    for(account a :lstAcc){
        if(a.contacts.size()>0)
            lstAccountToUpdate.add(a);
    }
}

udpate lstAccountToUpdate with checkbox as false

Let me know if this works.

Thanks
Ashish
Sainath VenkatSainath Venkat
Hi Jainam,

When I create account then Checkbox__c will be checked.
Now I will add First Contact C1 with email xyz@gmail.com
Now I will add Second Contact C2 with email xyz@gmail.com. since both contacts are having same email id i.e duplicate checkbox__c will get unchecked and its working perfectly.
Now I will update the Contact C2 with email abc@gmail.com, now both contacts are having different email id's and checkbox__c should get checked now which is not happening.
Jainam ContractorJainam Contractor
Hi Sai,

The latest handler code i shared will do that for you.

It works fine for me.

Can you please check using that code.

The code that you had did not had logic to check the Checkbox field on rectifying the Duplicate email hence it did not worked.

Please check with that code and let me know.

Thanks.
NitishNitish
Hi Sainath,

I hope this code will work fine for you.
Trigger contactDuplicateTrigger on Contact(before insert,before update){
    
    
        
        Set<Id> parentId=new Set<Id>();
        for( Contact c:Trigger.new){
            parentId.add(c.accountId);
        }
        
        List<Contact> conList=[SELECT Email From Contact WHERE accountId in : parentId];
        Set<String> emailSet=new Set<String>();
        for(Contact c1:conList){
            emailSet.add(c1.Email);
        }
        List<Account> accList=new List<Account>();
        for(Contact con:Trigger.new){
        
            if(emailSet.contains(con.Email)){
                Account acc=new Account();
                acc.DuplicateContact__c=false;
                acc.Id=con.accountId;
                accList.add(acc);
            }else{
                Account acc=new Account();
                acc.DuplicateContact__c=true;
                acc.Id=con.accountId;
                accList.add(acc);
            }
        }
        if(accList.size()>0){
            update accList;
        }
        
    
    
}
Let me know in case of any query.
Thanks,
Nitish
Jay Parikh 36Jay Parikh 36
Hi Sai , Here is a apex trigger and handler class :
 
=====Apex trigger ======

trigger ContactTrigger  on Contact (after insert,after update) {
   if(trigger.isafter && (trigger.isinsert || trigger.isupdate)){
       Handler_ContactDuplicate.UpdateAccount(trigger.new);
   }
}


======Handler class=======

Public class Handler_ContactDuplicate {
   public static void UpdateAccount (list < Contact> ctLst){
   map<id,contact> maptoAct = new map <id,contact>();
   list <account> acttoUpdate = new list <account>  ();
   set<string> emailstring = new set <string> ();
   account ac = new account() ;
      for(contact ct : ctLst){
          if(ct.AccountId != null && ct.Email != null){
               maptoAct.put(ct.Id,ct );
               emailstring.add(ct.Email);
               
          }
      
    list <contact> ctlstfind =[select id , AccountId ,Email from contact where Email in: emailstring ]; 
    
   
    
      if(ctlstfind.size() == 1){
        
        ac.id = maptoAct.get(ct.Id).AccountId;
        ac.Duplicate_contact__c =true ;
       
       
      }
      else {
        ac.id = maptoAct.get(ct.Id).AccountId;
        ac.Duplicate_contact__c =false ; 
        
        }
       acttoUpdate.add(ac); 
        
      }
     if(!acttoUpdate.isempty()){
        update acttoUpdate;
     } 
   }
}