function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
CKRCKR 

Trigger help to limit Number of cases to be created in a month per user

Hi All
Here is my trigger to limit a user to create only 10 cases in a month,it is half working accordingly, but i would like to put the logic in the apex class which is currently in the trigger, more over my trigger is restricting the users to create cases when they exceeded specified limit but i am seeing the first line of error 'Invalid Date' which is unexpected along with the custom error message that i have written in the trigger.
User-added image
 
Trigger LimitNoOfCases on case(Before insert){
    If (Trigger.IsInsert){
    Integer MonthNumber = Date.Today().Month();
    Integer YearNumber = Date.Today().Year();
    Integer MaxCases = Integer.valueof(System.Label.MaxCasesLimit);//configured maximum number of cases per user by creating Custom label.
    Id Xuser = UserInfo.Getuserid();
    User Usr = [select name from user where id=:userinfo.getuserid()];
    List<Case> LstCase = [select id,CreatedById,CreatedDate from case where CALENDAR_YEAR(CreatedDate) =:YearNumber and CALENDAR_MONTH(CreatedDate)=:monthnumber and CreatedById=:UserInfo.GetUserId()];
 
    If (Lstcase.Size()>=MaxCases)         
   {   
      Trigger.New[0].addError('Dear user you have exceeded the maximum number of cases allowed this month.');
   }  
     
  }
}

 
Best Answer chosen by CKR
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi CKR,

This is the trigger I have written according to bes practise,
 
trigger CaseTrigger on Case (before insert) {
    if(Trigger.IsInsert && Trigger.isBefore)
    	CaseTriggerHandler.limitNoOfCases(Trigger.New);    
}

And this is the trigger handler class,
 
public class CaseTriggerHandler {
    public static void LimitNoOfCases(List<Case> caseList) {
        Integer monthNumber = Date.Today().Month();
        Integer yearNumber = Date.Today().Year();
        Integer maxCases = 10;
        List<Case> thisMonthCaseList = [select id,CreatedById,CreatedDate from case where CALENDAR_YEAR(CreatedDate) =:YearNumber and CALENDAR_MONTH(CreatedDate)=:monthnumber and CreatedById=:UserInfo.GetUserId()];
        
        if (thisMonthCaseList.Size()>=maxCases)         
            caseList[0].addError('Dear user you have exceeded the maximum number of cases allowed this month.');
    }
}

Logic is almost same. I have changed some variable names according to best practise. Please save the trigger handler class before saving the trigger.

Thanks & Regards,
Prosenjit

All Answers

Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi CKR,

First line of error is actually 'Invalid Data' not 'Invalid Date'. I think this is the style of trigger by which we can see errors and your code is fine. If you want to write any trigger handlers then I can help . 

Thanks and Regards,

Prosenjit
CKRCKR
Hi @Prosenjit.....it was just a typo mistake hope you got my intention,,yes,, i would like to have trigger handlers for my trigger.

Thanks
CKR
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi CKR,

This is the trigger I have written according to bes practise,
 
trigger CaseTrigger on Case (before insert) {
    if(Trigger.IsInsert && Trigger.isBefore)
    	CaseTriggerHandler.limitNoOfCases(Trigger.New);    
}

And this is the trigger handler class,
 
public class CaseTriggerHandler {
    public static void LimitNoOfCases(List<Case> caseList) {
        Integer monthNumber = Date.Today().Month();
        Integer yearNumber = Date.Today().Year();
        Integer maxCases = 10;
        List<Case> thisMonthCaseList = [select id,CreatedById,CreatedDate from case where CALENDAR_YEAR(CreatedDate) =:YearNumber and CALENDAR_MONTH(CreatedDate)=:monthnumber and CreatedById=:UserInfo.GetUserId()];
        
        if (thisMonthCaseList.Size()>=maxCases)         
            caseList[0].addError('Dear user you have exceeded the maximum number of cases allowed this month.');
    }
}

Logic is almost same. I have changed some variable names according to best practise. Please save the trigger handler class before saving the trigger.

Thanks & Regards,
Prosenjit
This was selected as the best answer
CKRCKR
Thanks Prosenjit! it worked..but i was wondering why i am still seeing "Invalid Data" along with the custom messge is this the usual way or am i missing anything, coz usually we only see the custom message but not "Invalid Data" when compared to other trigger events, for eg, when we restrict users to update or insert records usually in before triggers.
Prosenjit Sarkar 7Prosenjit Sarkar 7
I think its because you are adding error to the first value of the Trigger.New List.
 
Salesforce BuzzLogicSalesforce BuzzLogic
Hi,Can you please say,How you are calculating number of records created by an user.
I have a Query.Where I should Restrict the user Not to create more than 200 records per week Using Trigger handler.
Salesforce BuzzLogicSalesforce BuzzLogic
Restrict user not to create more than 50 Accounts per week:

trigger RestrictUser on Account (before insert) {
    Integer maxAccounts = 50;
    if (maxAccounts != null) {
        Set<Id> userIds = new Set<Id>();
        Map<Id, Integer> accCountMap = new Map<Id, Integer>();
        for (Account acc: trigger.new) {
            userIds.add(acc.OwnerId);
            accCountMap.put(acc.OwnerId,0);
        }
        Map<Id, User> userMap = new Map<Id, User>([select Name from User where Id in :userIds]);
        for (AggregateResult result: [select count(Id),OwnerId from Account where CreatedDate = THIS_WEEK and OwnerId in :userIds group by OwnerId]) {
            accCountMap.put((Id) result.get('OwnerId'), (Integer) result.get('expr0'));
        }
        for (Account acc: trigger.new) {
            accCountMap.put(acc.OwnerId, accCountMap.get(acc.OwnerId) + 1);
            if (accCountMap.get(acc.OwnerId) > maxAccounts) {
                acc.addError('Too many Accounts created this month for user ' + userMap.get(acc.OwnerId).Name + '(' + acc.OwnerId + '): ' + maxAccounts);
            }
        }
    }
}


IF You Find My answer as Best Answer Please Like it as a best answer