1

I have created a custom account look up field on the lead object. I want to attach leads to existing accounts based on the company name.

So lets say if a lead comes-in and has filled out 'Salesforce' as the company name and an account already exists for Salesforce then the account look up field should automatically update to Salesforce.

The logic works like this:

1) Check if account name matching company name exists. 2) If yes, fetch account ID and map it to the account look up field on the lead. 3) Else, leave the field blank.

Here is the trigger I have been able to build so far after much research on the internet [still very new in writing triggers]:

Trigger Accname on Lead (before insert, before update) { 

    String leadaccountname;
    String companyName;
    for (Lead newLead : trigger.new){
        companyName = newLead.Company;leadaccountname = newLead.Account_Leads__c;
        break;
    }

      List<Account> lda = new List<Account>();  
       lda = [Select Id, Name from Account where Name =: companyName limit 1];

          if (lda.size() > 0){
           leadaccountname = lda[0].Name;
          }         
   }

I don't get any errors when I run it but the account field is not updating automatically.

2 Answers 2

2

You are on the right track, however, you're not making any edits to the Lead records anywhere in your trigger; instead, you are declaring variables and assigning values from the new Leads (companyName + leadAccountName). If you load more than 1 lead at a time, the variables are overwritten with the next lead, which will cause inaccuracies in your data.

Here's what I would do (added lots of comments to guide you). This is also "bulkified", so you can load 1 lead or 200 leads:

trigger AccName on Lead (before insert, before update) {

    //List to hold references to all leads invoking trigger...
    List<Lead> leadsToAddAccountId = new List<Lead>();

    //List to hold all company names from leads inserted/update
    //will be used in SOQL query to find accounts with same name     
    List<String> leadCompanyNames = new List<String>();

    //create a lookup map to use for populating Lead.Account_Leads__c fields with matching AccountId
    //Maps function simliar to Vlookups in Excel, where the 1st column is your key and the 2nd column is your value you want returned.   
    //It this case:
        //the 1st column will be the Account Name
        //the 2nd column will be the Account Id
    Map<String, Id> matchingAcctNames = new Map<String,Id>();


    //iterate over leads which invoked this trigger (basically any update/insert)... and add to list
    for (Lead newLead : trigger.new){

        //add lead to list to update with account Id before saving
        leadsToAddAccountId.add(newLead);

        //add lead company name to companyName list for SOQL Query to find matching accounts
        leadCompanyNames.add(newLead.CompanyName);

    }


    //Next, query accounts that have matching names and load to lookup Map
    for(Account acct : [Select Id, Name from Account where Name =: leadCompanyNames]){

        matchingAcctNames.put(acct.Name, acct.Id);

    }

    //finally, iterate over your leads and update Account_Leads__c field if name matches
    for(Lead myLead : leadsToAddAccountId ){

        myLead.Account_Leads__c = matchingAcctNames.get(myLead.CompanyName);

    }


}
3
  • The explanation helped a lot. I tried the below code and it worked. I got some errors in your and couldn't debug it. Trigger Accname on Lead (before insert, before update) { Account[] accts = [SELECT Name, id FROM Account]; for(Lead l : Trigger.new) { for(Integer i = 0; i < accts.size(); i++) { if(l.Company == accts[i].Name) { l.Account_Leads__c = accts[i].id; } else(System.debug('Not triggered.')); } } }
    – Mike
    Commented Aug 1, 2015 at 17:28
  • Odd. I ran this in a new dev environment to ensure it worked. I recommend double checking all field names AND ensure all validation rules (which I won't know you have) are not throwing the error. Typically, you'll get the error as you insert/update the record.
    – James
    Commented Aug 3, 2015 at 13:09
  • It works! So what if I want to create an account if it doesn't exist? Is that possible at all? and if yes, can anyone please guide me?
    – Asad Malik
    Commented Sep 28, 2016 at 21:37
0
trigger AccName on Lead (before insert, before update) {

   List<String> leadCompanyNames = new List<String>();
   Map<String, Id> matchingAcctNames = new Map<String,Id>();

    for (Lead newLead : trigger.new){
        leadCompanyNames.add(newLead.CompanyName);
    }
    for(Account acct : [Select Id, Name from Account where Name IN : leadCompanyNames]){
        matchingAcctNames.put(acct.Name, acct.Id);
    }
    for (Lead newLead : trigger.new){
        newLead.Account_Leads__c = matchingAcctNames.get(newLead.CompanyName); //corrected myLead with newLead
    }
}
5
  • @James : If I a not wrong, we can avoid the statement List<Lead> leadsToAddAccountId = new List<Lead>(); . And one more correction while Query Account object WHERE condition should be with "IN" not "=".
    – San
    Commented Aug 1, 2015 at 13:56
  • 1
    This example can be greatly reduced. I intentionally did so to help illustrate the process and guide mike inuitively so he has a framework for future challenges. Also, '=' and 'IN' are equivalent when using binding variables. developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…
    – James
    Commented Aug 3, 2015 at 13:06
  • 1
    @James : Thanks for the clarification on '=' and 'IN' when used for binding variables.
    – San
    Commented Aug 3, 2015 at 15:50
  • Glad it helped!
    – James
    Commented Aug 3, 2015 at 16:01
  • Error: Compile Error: Variable does not exist: myLead.CompanyName at line 13 column 52
    – Asad Malik
    Commented Sep 28, 2016 at 20:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .