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
Shree KShree K 

Sample trigger to limit the no of records from being created in an object especially on Case object

Hi All,
Can some provide me a sample before insert trigger code or references to limit a user (Logged in user) to create only 100 cases in a month,

Try this,
​trigger CaseCreateLimit on Case (after insert) {
    Set<Id> createdId= new Set<Id>();
    Date startOfMonth=;
    Map<Id, Integer> uCase= new Map<Id, Integer>();
    for(Case c :Trigger.New){
    List<AggregateResult> x=[SELECT COUNT(Status) c, CreatedById s FROM Case WHERE CreatedById IN :createdId AND CreatedDate >= :startOfMonth GROUP BY CreatedById];
    if(x.size() > 0){
        for(AggregateResult a :x){
            uCase.put( (Id)a.get('s'), (Integer)a.get('c'));
    for(Case c :Trigger.New){
        if(uCase.containsKey(c.CreatedById) && uCase.get(c.CreatedById) > 100){
            System.debug('This was supposed to be an error');
            c.addError('Sorry you cannot create more than 100 cases in a month');

Shree KShree K
Hi @badi,
Thanks for your time,That was not working,i have written in the following way which is working as per the requirement but does not look like efficient enough.
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(Usr.Name +' ('+UserInfo.GetUserId()+') has exceeded the maximum number of cases allowed this month.the current maximum is '+System.Label.MaxCasesLimit);