繁体   English   中英

Salesforce触发器以填充查找字段

[英]Salesforce Trigger to populate a lookup field

我正在尝试在Lead上创建salesforce触发器,该触发器将自动填充一个查找字段,如果存在与Lead's Company自定义字段同名的客户,则该查询字段会将当前Lead链接到现有客户。

这是我的代码:

trigger Link_Lead_To_Account on Lead (before insert ) {

 Set<String> whatIDs = new Set<String>();
 MAP<id,String> accountMap= new MAP<id,String>();

 // save the leads that have been triggered
    for (Lead l : Trigger.new) { 
     whatIDs.add(l.id);      
    }

List<Lead> leads = [SELECT Id,Company FROM Lead where ID=:whatIDs ];

// loop through the triggered leads, if the account.name == to lead.company then link the found account to the lead
 for (Integer i = 0; i <Trigger.new.size(); i++)
{
// System.Debug('++++++++++++++'+Trigger.new[i].company+Trigger.new[i].id);
   if(accountMap.get(Trigger.new[i].company)!=null)
   { 
       for(Account ac :[Select name,id from Account])
       {
           if(Trigger.new[i].Company==ac.Name)
           { 
               Trigger.new[i].Account__c=  ac.id;
                break;
           }
       }

   }
//  System.Debug('Trigger.new[i].Account__c::::'+Trigger.new[i].Account__c);
//  System.Debug('Trigger.new[i].company:::::'+Trigger.new[i].company);
//  System.Debug('Trigger.new[i].ID:::::'+Trigger.new[i].ID);

}
update leads;   

}

但这根本不起作用。 它引发以下错误:

Review all error messages below to correct your data.
Apex trigger Link_Lead_To_Account caused an unexpected exception, contact your administrator: Link_Lead_To_Account: execution of AfterInsert caused by: System.StringException: Invalid id: TestAccount2: External entry point

因为它要求Company字段是一个ID,但是当我编写一个ID时,它不会执行任何更改。

我设法解决了。 这是工作类,在构造器中将newLeads.Values()填充到before insert事件中的Trigger.new()值中:

public void LinkLeadToAccount() {

Set<String> companies = new Set<String>();
for (Lead l: newLeads.values()) {
    if (l.Company != null) companies.add(l.Company);
}

if (companies.size() > 0) {

    // Pick most recent Account where more than one with same name
    Map<String, Id> accountNameToId = new Map<String, Id>();
    for (Account a : [
            select Name, Id
            from Account
            where Name in :companies
            order by CreatedDate
            ]) {
        accountNameToId.put(a.Name, a.Id);
    }

    if (accountNameToId.size() > 0) {
        Lead[] updates = new Lead[] {};
        for (Lead l: newLeads.values()) {
            if (l.Company != null) {
                Id accountId = accountNameToId.get(l.Company);
                if (accountId != null) {
                    updates.add(new Lead(Id = l.Id, Account__c = accountId));
                }
            }
        }
        System.debug(' leads_to_update : ' + updates.size() + '   leads_to_update : ' +  updates);        
        update updates;
    }
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM