I have a custom object naming Time_Sheet__c having Start_Date__c (Date field) & End_Date__c (Date field) as two of its custom fields. Please help me with suggesting an Apex code to check the creation of more than two records with same Start_Date_c (Date field) for at least a week. I want my record to allow the users to create more than one record but should not duplicate with the Start_Date_c (Date field) value (i.e., No two records with similar Start date but similar created date is allowed). I had tried the below mentioned code to achieve my requirement, but this code checks for similar created date:

      for(Time_Sheet__c a:Trigger.new)
        string uid = userinfo.getName();
         List<Time_Sheet__c> acc=[select Id, CreatedDate, Owner.Name,   Start_Date__c from Time_Sheet__c where (Owner.Name = :uid AND CreatedDate = THIS_WEEK)];
               a.adderror('One record is already created for the Day For ' + uid);
   } ```
  • Have you considered using Duplicate Rule? Commented May 16, 2020 at 1:25
  • @HengkyIlawan yes I had tried making field value unique. Can you suggest me any other Duplication Rule i can use? Commented May 20, 2020 at 6:09
  • I was referring to the Duplicate Rule feature: help.salesforce.com/… Commented May 20, 2020 at 8:54

1 Answer 1


First of all let me tell you it's not recommendable and doesn't come under best practices to query inside a for loop.

You have made the query filtering all the records created this week, if you're ok with the records it's giving back then its ok. If not, then please try to put query filter as:

CreatedDate = LAST_7_DAYS

instead of :

CreatedDate = THIS_WEEK 

Also please try the below code and check if it fulfils your functionality:

Set<Date> startDates = new Set<Date>();     //fetches all the current records start dates
String uName = userinfo.getName();
Integer Counter =0;

for(Time_Sheet__c tsRecords : [select Id, CreatedDate, Owner.Name,Start_Date__c from Time_Sheet__c where Owner.Name = :uid AND CreatedDate = THIS_WEEK]){

if(lengthOfList > 0){
    for(Time_Sheet__c ts : Trigger.new){
        for(Date d : startDates){
            if(ts.Start_date__c.daysBetween(d) < 7){
            ts.adderror('One record is already created for the Day For ' + uName);
            Counter = 0;
            startDates.add(ts.Start_Date__c);     // if you don't want to add error and also want to check the current iteration date from the next iteration onwards

Note: Although it's not the efficient code for the problem as it includes nested for loop, I hope you can eliminate this by using MAPs data structure accordingly.

  • Thanks for the response, but this answer seems to have some problem in it. The Set criterion won't work for me. Commented May 15, 2020 at 12:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .