+ Start a Discussion

Is this impossible?

Ok so my knowledge of Apex Triggers has improved over the years (mainly thanks to help from people on here) however I cant get this one:


I need a trigger to change the owner on an account when the Type is changed to 'Customer'. The way I need to trigger to decide who to change the owner to by counting the number of  accounts where type is 'Customer' for each Owner 1, Owner 2 and Owner 3 and then assigning the ownership to the Owner with the least Accounts. Where each owner has the same number of accounts, then it should assign ownership to the person who had an account assigned the longest time ago.


is this possible?


 Hello Steven,


This seems, with a few potential concerns, doable.  There is a few questions I have.


1) Are you currently keeping track of when a Account was assigned to an employee?  In this example I made up a fake Date field, AssignedOnDate__c, to show how it might work.  If this field doesn't exist, there might be other ways but it depends a bit more on your dataset.


2) If multiple accounts are inserted/updated to type customer, do they all go to the lowest employee or do you want it to grant ownership to one, then recalculate to determine the lowest employee?  In this example, I give all Accounts to the lowest employee, but with a little more work you could make it recalculate per record.  


Eitherway, heres a rough draft of how I would start to go about this:


public static void setAccountOwnership(List<Account> triggeredAccounts){


//List of Accounts as Aggregated Results only of type Customer grouped by Owner and sorted lowest to highest.

transient AggregateResult[] groupedAccountOwners = [Select OwnerId, Count(Id) counter FROM Account WHERE type = 'Customer'  Group by OwnerId order by Count(Id)];


For (Account singleAccount: triggeredAccounts){

//If the triggered Account is of Type Customer and the other Customer Accounts already exist.  Set the Owner to the lowest one.

if (groupedAccountOwners.size() > 0 && singleAccount.Type == 'Customer'){

singleAccount.OwnerId = groupedAccountOwners[0].get('OwnerId');





Hope this helps.  If you have any additional questions please let me know and we can try and sort it out from there.  Best of luck!


Hi thanks for your reply. Your help is much apprecaited.


Re Q1 - Know i am not - but i guess I should do! We keep the previous owner ID but not the date changed. Its unlikely accounts will be re-assigned in bulk more for example when an opportunity is closed won - workflow then updates the account. - now i need the account to be allocated so i think the below word work fine.




I have copy and pasted your code to make a start but seem to be getting a lot or errors - am i missing something?