I am trying to limit my Users to only have 1000 Accounts each. I created the following trigger:

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()]; 

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

For the purpose of testing I put "if(accounts >3)..." But I noticed I am still able to change more than 3 Accounts to a user(lets call him Bob). The error only shows up when I am trying to switch the extra Account from Bobs name.

Is it possible to have the error display when I try to change a 4th Account TO Bob's name?

  • What does the system.debug return for accounts? Does it return a number greater than 3? What happens if you try to add/change a 5th/6th account to Bob? Does it only fail on the 4th, or only fail on insert? More info would help – Morgan Marchese Sep 29 '16 at 21:27
  • Are you logged in as bob when you are changing the account owner? Your count query goes by logged in user. Also you should change to after context or add trigger records to counts – Eric Sep 29 '16 at 22:19
  • this trigger is not bulkified and hence won't verify the rule on any batch operation (such as Import Wizard) – cropredy Sep 30 '16 at 0:09

You need to use after insert and after update trigger. In before triggers, the values are not updated yet in the databse

  • You could do before if you add the trigger context records to the totals – Eric Sep 29 '16 at 22:20
  • @Eric, that's true. But why bother. – Lance Shi Sep 29 '16 at 22:26
  • Who knows. I am sure someone will have a use case lol – Eric Sep 29 '16 at 22:27
  • @Eric it could be write some code though. You need to create a map of the count in the current trigger contest and adds up with the number of the existing ones in the database. Also need to consider about duplicate ones. Can be a bit of work. So I wouldn't recommend that unless there is a really good reason. – Lance Shi Sep 29 '16 at 22:33
  • @LanceShi - I am testing this out on Partial Sandbox, when the owner is being changed to me: it does not allow me to add a 4th Account to my ownership, BUT when I try it under another user, it allows them to have the 4th Account transfered. What's the reason behind that? – B.Wayne Sep 30 '16 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.