Skip to content

Instantly share code, notes, and snippets.

@pcon
Created November 11, 2014 14:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcon/8afe91eee8fde2d0fd15 to your computer and use it in GitHub Desktop.
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
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);
}
}
}
}
@ssssm83
Copy link

ssssm83 commented Mar 12, 2019

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