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 

Limit Number of Accounts Per User

I am trying to Limit the number of Protected Accounts a User should have under their ownership.  This is the trigger I created with the help of the SFDC Community 

trigger Limit1000AccountsForUsers on Account (before insert, before update) {
    Account accs = Trigger.new[0];

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

        if (accounts >3 ) {
            accs.addError('You are your limit of Accounts.');
        }
    }
}

But I noticed it only goes by the logged in user.  Is there a way to update the trigger so it limits the Protected Accounts regardless of the user?

 
Best Answer chosen by S_Batman
UC InnovationUC Innovation
Hi S_Batman,

You can change your query to look at the owner of the account that fired the trigger instead. This is what your query would look like:
 
trigger Limit1000AccountsForUsers on Account (before insert, before 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 >3 ) {
            accs.addError('You are your limit of Accounts.');
        }
    }
}

Please choose as best answer if this helped!

All Answers

UC InnovationUC Innovation
Hi S_Batman,

You can change your query to look at the owner of the account that fired the trigger instead. This is what your query would look like:
 
trigger Limit1000AccountsForUsers on Account (before insert, before 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 >3 ) {
            accs.addError('You are your limit of Accounts.');
        }
    }
}

Please choose as best answer if this helped!
This was selected as the best answer
S_BatmanS_Batman
That works really well!  Only thing I wanted to change on your code was after insert/update

Thanks
Ashique Khan 7Ashique Khan 7
@S_Batman - are you able to share the test class you wrote for this please? Thanks!
Jared.SoellJared.Soell
Would there be a simpler formula if you just wanted to limit a user (with a certain profile) to not be able to own more than 500 Accounts?