0

I want to avoid Creation or Deletion of Accounts in a specific month(for eg December). How can I achieve this. Because the createdDate is null in before Insert and addError does not run in after Insert, so how can we bring them both together. Please help me gys I am new to apex and this question was asked to me in interview.

1

Your interviewer may have been trying to trick you as the best answer is to use a Validation Rule on Account

Name: IsInvalidCreationMonth

Expression: MONTH(DATEVALUE(CreatedDate)) = 12

Error: Accounts can not be created in December
1

For starters, you should make sure you understand trigger frameworks in Salesforce and how your org can benefit from them. There are quite a few resources that already discuss these. Some good examples can be found in the answers to this question: Generic Apex Trigger

To answer your question, you could create a utility class/method that could accept a Datetime value and then return true if the passed value was an allowable time to create/delete an Account.

public class MyUtilityClass {

    public static Boolean isValidAccountCreateOrDeletePeriod(Datetime value) {
        // perform your custom logic here
        return value.month() != 12;
    }
}

You could then call this utility method from the class that stores your trigger logic. If the trigger is running during in beforeInsert context, you could pass the System.now() value. If you need to make sure accounts created in December aren't deleted, you could pass in the Account's created date value while running in beforeDelete context.

If your utility method returns false, you could then create your error message and inform the user of the issue.

You may also want to think about letting certain users bypass the trigger or allow some custom setting to control when the trigger is run (in case you need to perform data cleanup in December). Some questions on here already go in to those use cases: Bypass Triggers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.