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
tulasiram chtulasiram ch 

I wrote a trigger for posting an error message when user try to insert/update phone field with duplicate values those were already existed...

Insertion throwing error working fine but updation is not working can anyone give me a solution...
trigger duplicatePhoneOnCandidate on Candidate__c (before insert) 
{
    Map<String, Candidate__c> candidateMap = new Map<String, Candidate__c>();
    for(Candidate__c candidates: System.Trigger.new)
    {
    // Make sure we don't treat an Phone address that isn't changing during an update as a duplicate. 
        if(candidates.Phone__c != null && (System.Trigger.isInsert && System.Trigger.isUpdate || (candidates.Phone__c != System.Trigger.oldMap.get(candidates.Id).Phone__c)))
        //if(candidates.Phone__c != null && System.Trigger.isInsert)
        {
         // Make sure another new Candidate isn't also a duplicate 
        if(candidateMap.containsKey(candidates.Phone__c))
            {
            candidates.Phone__c.addError('Phone Already exists');
            }
            else
            {
        candidateMap.put(candidates.Phone__c, candidates) ;   
            }
        }

    }  // Using a single database query, find all the Candidate in
        // the database that have the same Phone address as any
        // of the Candidate being inserted or updated.
    for (Candidate__c can : [SELECT Phone__c FROM Candidate__c
                      WHERE Phone__c IN :candidateMap.KeySet()]) {
        Candidate__c newCan = candidateMap.get(can.Phone__c);
        newCan.Phone__c.addError('Candidate record have already this pone number.');
    }
}
Best Answer chosen by tulasiram ch
Amit Chaudhary 8Amit Chaudhary 8
Try to update below code
trigger duplicatePhoneOnCandidate on Candidate__c (before insert ,before update) 
{
    Map<String, Candidate__c> candidateMap = new Map<String, Candidate__c>();
	
	Set<Id> setId = new Set<ID>();
    for(Candidate__c candidates: System.Trigger.new)
    {
		setId.add(candidates.Id);
		
		if( (candidates.Phone__c != null && System.Trigger.isInsert ) || ( System.Trigger.isUpdate  && candidates.Phone__c != System.Trigger.oldMap.get(candidates.Id).Phone__c ) )
		{
			if(candidateMap.containsKey(candidates.Phone__c))
			{
				candidates.Phone__c.addError('Phone Already exists');
			}
			else
			{
				candidateMap.put(candidates.Phone__c, candidates) ;   
			}
		}

    }  
	
	// Using a single database query, find all the Candidate in
	// the database that have the same Phone address as any
	// of the Candidate being inserted or updated.
    for ( Candidate__c can : [SELECT Phone__c FROM Candidate__c   WHERE Phone__c IN :candidateMap.KeySet() and Id not in :setId ] ) 
	{
        Candidate__c newCan = candidateMap.get(can.Phone__c);
        newCan.Phone__c.addError('Candidate record have already this pone number.');
    }
}

Let us know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
You did not added before update event in your trigger
trigger duplicatePhoneOnCandidate on Candidate__c (before insert ,before update)
 
Amit Chaudhary 8Amit Chaudhary 8
Try to update below code
trigger duplicatePhoneOnCandidate on Candidate__c (before insert ,before update) 
{
    Map<String, Candidate__c> candidateMap = new Map<String, Candidate__c>();
	
	Set<Id> setId = new Set<ID>();
    for(Candidate__c candidates: System.Trigger.new)
    {
		setId.add(candidates.Id);
		
		if( (candidates.Phone__c != null && System.Trigger.isInsert ) || ( System.Trigger.isUpdate  && candidates.Phone__c != System.Trigger.oldMap.get(candidates.Id).Phone__c ) )
		{
			if(candidateMap.containsKey(candidates.Phone__c))
			{
				candidates.Phone__c.addError('Phone Already exists');
			}
			else
			{
				candidateMap.put(candidates.Phone__c, candidates) ;   
			}
		}

    }  
	
	// Using a single database query, find all the Candidate in
	// the database that have the same Phone address as any
	// of the Candidate being inserted or updated.
    for ( Candidate__c can : [SELECT Phone__c FROM Candidate__c   WHERE Phone__c IN :candidateMap.KeySet() and Id not in :setId ] ) 
	{
        Candidate__c newCan = candidateMap.get(can.Phone__c);
        newCan.Phone__c.addError('Candidate record have already this pone number.');
    }
}

Let us know if this will help you
 
This was selected as the best answer
tulasiram chtulasiram ch
Thanks Amit.....But i am getting this error at the time of insertion

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger duplicatePhoneOnCandidate caused an unexpected exception, contact your administrator: duplicatePhoneOnCandidate: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.duplicatePhoneOnCandidate: line 9, column 1

And can You tell me How it works :
if( (candidates.Phone__c != null && System.Trigger.isInsert ) || ( System.Trigger.isUpdate  && candidates.Phone__c != System.Trigger.oldMap.get(candidates.Id).Phone__c ) )
we are inserting candidates  then why we are checking that statement with candidates.Id
and what it means Trigger.oldMap.get(candidates.id).Phone__c 
rajat Maheshwari 6rajat Maheshwari 6

Hi tulasiram,

Below is the code, which will help you:)

trigger duplicatePhoneOnCandidate on Candidate__c (before insert ,before update) 
{
    Map<String, List<Candidate__c>> candidateMap = new Map<String, List<Candidate__c>>();
Set<String> checkPhone_Insert = new Set<String>();
Set<String> checkPhone_Update = new Set<String>();
Set<id> checkId = new Set<Id>();
Map<Id,Candidate__c> candidateRecd_InsertMap = new Map<Id,Candidate__c>();
Map<Id,Candidate__c> candidateRecd_UpdateMap = new Map<Id,Candidate__c>();

  
if(Trigger.isbefore && Trigger.isInsert)
 {
  for(Candidate__c candidates:Trigger.new)
    {
        if(candidates.Phone!=null
		checkPhone_Insert.add(candidates.Phone);
    }
}

 
if(Trigger.isbefore && Trigger.isUpdate)
  {
    
      for(Candidate__c candidates:Trigger.new)
        {
       
      if(candidates.Phone!=null && candidates.Phone!=Trigger.oldMap.get(candidates.id).Phone)
       {
           checkPhone_Update .add(candidates.Phone);
           checkId.add(candidates.id);
       }

   }
}

if(checkPhone_Insert!=null && !checkPhone_Insert.isEmpty())
   {
      for(Candidate__c  candidateRecd_Insert : [Select Id,Phone from Candidate__c where Phone IN:checkPhone_Insert])
          {
                candidateRecd_InsertMap.put(candidateRecd_Insert.Phone,candidateRecd_Insert);
           }
   }

if(checkPhone_Update!=null && !checkPhone_Update.isEmpty())
  {
     for(Candidate__c candidateRecd_Update : [Select Id,Phone from Candidate__c where Phone IN:checkPhone_Update And Id Not IN: checkId])
        {
            candidateRecd_UpdateMap.put(candidateRecd_Update.Phone,candidateRecd_Update);
          }

   }

for(Candidate__c candidate_Record : Trigger.new)
  {
     if(candidate_Record.Phone!=null && candidateRecd_InsertMap!=null && candidateRecd_InsertMap.containsKey(candidate_Record.Phone) && candidateRecd_InsertMap.get(candidate_Record.Phone)!=null)
         {
             candidate_Record.addError('Phone Number already exist');
         }

if(candidate_Record.Phone!=null && candidateRecd_UpdateMap!=null && candidateRecd_UpdateMap.containsKey(candidate_Record.Phone) && candidateRecd_UpdateMap.get(candidate_Record.Phone)!=null)
     {
         candidate_Record.addError('Phone Number already exist');
     }
 }

}

Thanks
Rajat Maheshwari
rajatzmaheshwari@gmail.com
Dinesh RDinesh R
Hi tulasiram ch

Your task in only as finding the duplicate means you can use the below code.


trigger CandidateTrigger on Candidate__c (before insert, before update) {
    Map<string,id> candidateMap = new Map<string, id>();
    set<string>candidatephoneSet = new set<string>();
    
    for(Candidate__c Candidate :Trigger.new){
        if(Candidate.CandidatePhone__c !=null){
            candidatephoneSet.add(Candidate.CandidatePhone__c);
        }
    }
    for(Candidate__c Can :[SELECT id,Name,CandidatePhone__c FROm Candidate__c WHERE CandidatePhone__c In : candidatephoneSet]){
        candidateMap.put(Can.CandidatePhone__c, Can.Id);
    }
    for(Candidate__c candidateNew : Trigger.new){
        if(candidateMap.containsKey(candidateNew.CandidatePhone__c) && candidateMap.get(candidateNew.CandidatePhone__c) !=candidateNew.Id){
            candidateNew.CandidatePhone__c.addError('Already Phone Exist');
        }
    }
}


Please let me know if still facing any issues.
Thanks
Dinesh

 
Dinesh RDinesh R
Hi tulasiram ch
Also, I have seen Amit Chaudhary code it also working.Please add the event before the update.
I have added my code for the simple for finding the duplication.

Please let me know if this will help or not.

Thanks
Dinesh
tulasiram chtulasiram ch
Amith can you suggest me how to check email and Phone using same trigger
rajat Maheshwari 6rajat Maheshwari 6

Hi TulsiRam,

Amit code will work best in cas eof update operation, but when you will try for insert opeartion, It will give null pointer exception error, as Record Id is not genertaed yet in before insert operation and you are trying to check "candidates.Id" in logic, That's why It gives null pointer exception.

Please let me know, in case of any help :)

Thanks

Amit Chaudhary 8Amit Chaudhary 8
Hi TulsiRam,

Even i tested above code which is working fine for me
trigger duplicatePhoneOnCandidate on Candidate__c(before insert ,before update) 
{
    Map<String, Candidate__c> candidateMap = new Map<String, Candidate__c>();
    
    Set<Id> setId = new Set<ID>();
    for(Candidate__c candidates: System.Trigger.new)
    {
        setId.add(candidates.Id);
        
        if( (candidates.Phone__c != null && System.Trigger.isInsert ) || ( System.Trigger.isUpdate  && candidates.Phone__c != System.Trigger.oldMap.get(candidates.Id).Phone__c ) )
        {
            if(candidateMap.containsKey(candidates.Phone__c))
            {
                candidates.Phone__c.addError('Phone Already exists');
            }
            else
            {
                candidateMap.put(candidates.Phone__c, candidates) ;   
            }
        }

    }  
    
    // Using a single database query, find all the Candidate in
    // the database that have the same Phone address as any
    // of the Candidate being inserted or updated.
    for ( Candidate__c can : [SELECT Phone__c FROM Candidate__c WHERE Phone__c IN :candidateMap.KeySet() and Id not in :setId ] ) 
    {
        Candidate__c newCan = candidateMap.get(can.Phone__c);
        newCan.Phone__c.addError('Candidate record have already this pone number.');
    }
}



Please try below code for email and Phone
Trigger duplicatePhoneOnCandidate on Candidate__c(before insert, before update) 
{
    Set<ID> setId = new Set<ID>();
    set<String> setEmail = new Set<String>();
    set<String> setPhone = new Set<String>();
    
    for (Candidate__c cand : Trigger.new) 
    {
        if (cand.Email__c != null && cand.Phone__c !=null) 
        {
            setId.add(cand.id);
            setEmail.add(cand.Email__c );
            setPhone.add(cand.Phone__c );
            
        }
    }
    
    if(setId.size() > 0 )
    {
        List<Candidate__c> lstOldCand  = [select email__c,phone__c,id from Candidate__c where email__c in :setEmail and phone__c in :setPhone and Id not in :setId ];
        Map<String ,Candidate__c> MapStringWiseCont = new Map<String,Candidate__c>();
        
        for(Candidate__c cand : lstOldCand  )
        {
            String key = cand.Email__c +'_'+cand.Phone__c;
            MapStringWiseCont.put(key,cand);
        }

        for (Candidate__c cand : Trigger.new) 
        {
            if (cand.Email__c != null && cand.Phone__c !=null) 
            {
                String key = cand.Email__c +'_'+cand.Phone__c;
                 if(MapStringWiseCont.containsKey(key))
                 {
                    Candidate__c contOld = MapStringWiseCont.get(key);
                    String errorMessage = 'Duplicate contact found! Record ID is ' + contOld.Id;
                    cand.addError(errorMessage);
                 }
            }
        }    
    }
}

Let us know if this will helps you
 
tulasiram chtulasiram ch
Yeah amith working fine thank you....
tulasiram chtulasiram ch
Amith its taking Null values as duplicates when i try to update with a null value
tulasiram chtulasiram ch
Rajat Maheswari i am getting below example with your code....
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger duplicateTriggeronCandidate caused an unexpected exception, contact your administrator: duplicateTriggeronCandidate: execution of BeforeInsert caused by: System.StringException: Invalid id: (996) 565-6565: External entry point