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
S_BatmanS_Batman 

Having Limited Protect Accounts per User

trigger Limit1000AccountsForUsers on Account (after insert, after update)
{Account accs = Trigger.new[0];
string accountOwner = accs.OwnerId;

If(accs.Protected_Accounts__c == true){Integer accounts = [ SELECT COUNT()FROM Account WHERE Account.OwnerId=: accountOwner]; 
system.debug(accounts);

If(accounts > 2 ) {accs.addError('You already have 1000 Accounts in your ownership. Please remove one Account before adding a new.');
}
}
}

We have the following code to limit number of Protected Accounts to 1000 per user.  I have one user that has 950 Protected Accounts and 50 unprotected Accounts.  When I try to add another protected Account I am getting the error 'You already have 1000 Accounts in your ownership. Please remove one Account before adding a new.'.

I only want this error to occur when a user tries to add over 1000 Protected Accounts.

Is there something missing within the Apex?
Prasad Avala(SFDC-SF)Prasad Avala(SFDC-SF)
Batman,
Please see below change :

If(accs.Protected_Accounts__c == true){Integer accounts = [ SELECT COUNT()FROM Account WHERE Account.OwnerId=: accountOwner AND Protected_Accounts__c = True];