0

Can anyone help me with a validation rule, which prevents the creation of more than one record per day? I have tried using different Validation rules, but none of them worked as expected. I know this question has been answered many times, but none of the answers were helpful for me.

3
  • You cannot do this with validation rule, you will need to write an Apex trigger for this. Apr 16, 2020 at 14:14
  • @rahulgawale can you help me with the apex code, and where to use the apex code? Apr 16, 2020 at 14:24
  • Find in this post, an answer by Tushar Sharma Apr 16, 2020 at 14:26

2 Answers 2

1

A validation rule would only work in conjunction with another object which will store the last date at which the last record was inserted. This would be very clunky and computationally expensive to implement.

A cleaner solution would be to implement this in a trigger before insert.

class CustomObjectTriggerHandler {

public void beforeInsert(List<Custom_Object__c> newList) {
    List<Custom_Object__c> mostRecentlyCreatedRecord = new List<Custom_Object__c>(
    [SELECT Id FROM Custom_Object__c WHERE CreatedDate = TODAY LIMIT 1]
    );
    if (!mostRecentlyCreatedRecord.isEmpty()) {
        for (Custom_Object__c obj : newList) {
            obj.addError('Only one can be created per day');
        }
    }
}
1

You cannot do this with validation rule, Either you need to write an Apex trigger or you need to set up a process builder and call an apex class from that process.

Sample Code:

Public static beforeinsertHandler(List<Sobjectname> Records)
{
LIST details=[Select id from sobject where createddate=TODAY LIMIT 1];
If(For sobjectiterator: records)
{
If(details <> null && !details.isEmpty())
{
sobjectiterator.addError('Error message');
}
}
}

For Refernce: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/

5
  • I think you mean WHERE CreatedDate = TODAY. If you use =:System.Today() I believe you are looking for an exact datetime match down to the millisecond.... Apr 16, 2020 at 14:33
  • Nope it will return only today's date
    – Pavan tej
    Apr 16, 2020 at 14:47
  • details <> null unnecessary... the variable will never be null.
    – sfdcfox
    Apr 16, 2020 at 14:48
  • Good catch but usually I write as a precaution
    – Pavan tej
    Apr 16, 2020 at 15:03
  • TODAY and System.Today() are different, try it for yourself. System.debug('System.today() : + [SELECT Id FROM Asset WHERE LastModifiedDate = :System.today()]); System.debug('TODAY : ' + [SELECT Id FROM Asset WHERE LastModifiedDate = TODAY]); Prints out System.today() : () and TODAY : (Asset:{Id=02i3B000003rhL8QAI, RecordTypeId=0123B0000005uztQAA}) Apr 16, 2020 at 15:11

You must log in to answer this question.

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