Problem statement:
I need to prevent the user from creating more than 10 Opportunities per month.
public static void createOpportunity(List<Opportunity> newOpportunityList){
for(Opportunity newOpportunity : newOpportunityList){
for(AggregateResult result : [SELECT COUNT(CreatedById) FROM Opportunity WHERE createdByID=: System.UserInfo.getUserId() AND createdDate = THIS_Month]){
Integer count = (Integer)result.get('expr0');
if(count > Integer.valueOf(System.Label.OpportunityThreshold)){
newOpportunity.addError('This user has had more than 10 opportunity in this month') ;
}
}
}
}
Primarily, I want to learn if there's a better way to use loops here.