Created
November 11, 2014 14:34
-
-
Save pcon/8afe91eee8fde2d0fd15 to your computer and use it in GitHub Desktop.
Trigger code to make it so that a User can only create X number of cases per month
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger MaxCases on Case (before insert) { | |
Integer maxCases = null; | |
CaseSettings__c settings = CaseSettings__c.getValues('default'); | |
if (settings != null) { | |
maxCases = Integer.valueOf(settings.MaxCases__c); | |
} | |
if (maxCases != null) { | |
Set<Id> userIds = new Set<Id>(); | |
Map<Id, Integer> caseCountMap = new Map<Id, Integer>(); | |
for (Case c: trigger.new) { | |
userIds.add(c.OwnerId); | |
caseCountMap.put(c.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 Case | |
where CreatedDate = THIS_MONTH and | |
OwnerId in :userIds | |
group by OwnerId | |
]) { | |
caseCountMap.put((Id) result.get('OwnerId'), (Integer) result.get('expr0')); | |
} | |
for (Case c: trigger.new) { | |
caseCountMap.put(c.OwnerId, caseCountMap.get(c.OwnerId) + 1); | |
if (caseCountMap.get(c.OwnerId) > maxCases) { | |
c.addError('Too many cases created this month for user ' + userMap.get(c.OwnerId).Name + '(' + c.OwnerId + '): ' + maxCases); | |
} | |
} | |
} | |
} |
This can be very simple by just one query:
trigger MaxCases on Case (before insert) {
Integer maxCases = null;
CaseSettings__c settings = CaseSettings__c.getValues('default');
if (settings != null) {
maxCases = Integer.valueOf(settings.MaxCases__c);
}
Map<Id,AggregateResult> caseCountMap = new Map<id,AggregateResult>([select count(Id), OwnerId Id, Owner.Name from Case where CreatedDate = THIS_MONTH group by OwnerId,Owner.Name having count(id) >: maxCases]);
//{00Gg0000001aNhLEAU=AggregateResult:{expr0=7, Id=00Gg0000001aNhLEAU, Name=Test}}
for (Case c: trigger.new) {
AggregateResult ar = caseCountMap.get(c.OwnerId);
if (ar != null) {
c.addError('Too many cases created this month for user ' + ar.get('Name') + '(' + c.OwnerId + '): ' + maxCases);
}
}
}
Hi,
I just want to know what values you have given in default in custom settings?
CaseSettings__c settings = CaseSettings__c.getValues('default');
It shows null values for me.
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Was it necessary to initiate caseCountMap on line 15 with value of 0 when you replace all of the values in caseCountMap on line 32 using the same set of UserID's?