Monday, August 24, 2015

Preventing duplicates by checking two fields

---------------------------------------------------------------------------------------------------------------------

Scenario: Single Contact should not add same Date more than Once.
              This scenario is based on Timesheet filling... system   should not allow user to add                     same date again and again

___________________________________________________________________________________



trigger DuplicateCheckTrigger on Timesheet__c (before insert) {
       Set<string> nameSet = new Set<string>();
     
       Map<id,Date> dtr=new  Map<id,Date>();
       map<Id,List<Timesheet__c>> avoiddups=new map<Id,List<Timesheet__c>>();

        for(Timesheet__c times : trigger.new){
  if(!dtr.containskey(times.ContactId__c)){

  dtr.put(times.ContactId__c,times.StartDate__c);
  }
 
            nameSet.add(times.ContactId__c );      
         
        }

   

      system.debug('%%%%%%%%%%%%%nameSet%%%%%%%%%%%%%%'+nameSet);
        List<Timesheet__c> timList = new List<Timesheet__c>(
            [select id,ContactId__c , StartDate__c,ContactId__r.name from Timesheet__c where ContactId__c in:nameSet]);

            system.debug('%%%%%%%%%%%%%timList%%%%%%%%%%%%%%'+timList);
         
        for(Timesheet__c timess : timList){

     
        if(avoiddups.containskey(timess.ContactId__c)){
   avoiddups.get(timess.ContactId__c).add(timess);
   }
   else{
   avoiddups.put(timess.ContactId__c,new List<Timesheet__c>{timess});
 
   }
}
system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+avoiddups.values());
system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+dtr.values());
  For(Timesheet__c str:trigger.new)
  {
    For(Timesheet__c dt:avoiddups.get(str))
    {
 
     if(dt.StartDate__c==dtr.get(str.ContactId__c))
     {
   
     system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+dt.StartDate__c+'^^^^^^^^^^^^^^^^^^^^^^^^'+dtr.get(str.ContactId__c));
   
     str.StartDate__c.adderror('This date is already specified to this contact: '+dt.ContactId__r.Name);
     }
 
 
    }


  }


}

No comments:

Post a Comment