2016-01-12 30 views
0

我試圖在潛在客戶上創建salesforce觸發器,該潛在客戶自動填充查找字段,該字段將當前潛在客戶關聯到現有帳戶,如果存在與主導公司自定義名稱相同的帳戶領域。Salesforce觸發器來填充查找字段

這是我的代碼:

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 

,因爲它要求公司字段是一個ID,但是當我寫一個ID但這並沒有進行任何更改。

+0

你爲什麼更新導致對象? whatIDs將一直是空的。我相信在觸發器還沒有ID之前。 –

+0

什麼是TestAccount2? –

+0

testAccount2是我用於測試目的的帳戶的名稱 –

回答

0

我設法解決它。 這是newLeads.Values()被填充在構造函數的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; 
    } 
} 

}

+0

它工作正常嗎?你測試過了嗎? –

+0

是的,除了批量進口/更新之外,它運作良好。因此我將不得不更新它。 –

+0

我更新到最終的工作版本 –