User Story
As a Salesforce administrator, I want to ensure that no new Account records are created outside of business hours in order to maintain data accuracy and prevent errors or delays in processing. Therefore, I need to create a trigger that will check the current date and time against the default BusinessHours record and prevent record insertion if it falls outside of business hours.
Code
trigger AccountTrigger on Account (before insert) {
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
for(Account ac : Trigger.new){
if (!BusinessHours.isWithin(bh.Id, DateTime.now())) {
ac.addError('Business hours');
}
}
}