[SalesForce] Trigger to populate custom Account field from AccountTeamMember

I am attempting to create a trigger on the Account object to populate a custom lookup field called Sales Rep. I am trying to pull the name of the Sales Rep (based on role, Sales Rep) on the Account Team and populate it in this field. I am extremely new to Apex and cannot get this right. Here is what I have attempted…with no success. I have not even tried to add the if statement to identify the role yet.

trigger SalesRep on Account (before update) 
{
    Set<Id> accountIds = new Set<Id>();
    for(Account a : Trigger.new)
    {
        accountIds.add(a.Sales_Rep__c);
    }

    Map<Id, Account> getaccsandtmember = new Map<Id, Account>([Select Id,(Select UserID From Account.AccountTeamMembers)]);
    if (a.Sales_Rep__c == null) {

        a.Sales_Rep__c = AccountTeamMember.id;
    }
    }

This is the Class

public class teammembers
{
  public List<Account> getaccsandtmember()
  {
      List<Account> accounts = [Select Id,(Select TeamMemberRole, UserID From Account.AccountTeamMembers), Name from Account];
      return accounts;
  }
}

Please Help!!

Best Answer

There are a couple of things wrong with this code.

Let me start off with the teammembers class you made. Why do you have this class? Where is it used? Your trigger doesn't reference it so I think you can remove that class.

Then for your trigger itself. I believe the business requirement is that the Sales_Rep__c field on account get's filled when an account team member is created with the role "Sales Rep".

If that is the requirement, the first issue is that you run your trigger on the account object and not the account team meber. That being said, you cannot have triggers on the account team meber object. Do please vote for this idea:

https://success.salesforce.com/ideaView?id=08730000000YR8IAAW.

So this makes it an interesting business requirement.

Also, to point out some other issues with how you wrote the trigger. (good learning) You were making a loop to get the accountIds but instead of adding the account ID, you added the Sales_rep__c lookup value. Which would be empty because you wanted to fill that value. Then, your query itself didn't have a from or where clause. In the part after your query, all of a sudden you are not handling bulk anymore.

Now, to come to a solution. Since you can't have triggers on account team members, you will most likely need to have some code that runs in batch.

Then, to build your code itself, I advise you to first write in comments (just plain english) what your code should do. Then go through the documentation how you need to do these things.

When writing a batch, also make sure that you just process those records that need to be processed.

Hope this sets you in the right direction.

Related Topic