2015-03-25 117 views
0

我已經觸發了更新聯繫人標識的個人帳戶及其用於個人帳戶的工作,它正在人帳戶上填充聯繫人標識字段。嘗試取消引用空對象Salesforce

問題是它給業務和僱主帳戶記錄類型的錯誤,我也插入了記錄類型的支票。但它仍然給人一種錯誤

on Error: Invalid Data.

Review all error messages below to correct your data.

Apex trigger UpdateContactID caused an unexpected exception, contact your administrator: UpdateContactID: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateContactID: line 41, column 1

觸發低於:

trigger UpdateContactID on Account (after insert, after update) 
{ 

//Identify applicable record type 
    RecordType PersonAccount = [SELECT Id FROM RecordType WHERE SobjectType='Account' AND Name = 'Career Champion Account' limit 1]; 

List<Account> toUpdate = new List<Account>(); 

if(trigger.isInsert) 
{ 



List<String> newAccountIDList = new List<String>(); 


// Taking all account IDs in collection 
for(Account acct: Trigger.new) 
{ 
    newAccountIDList.add(acct.ID); 
} 

// Fetching contacts against the account IDs 
List<Contact> contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList];  


// Adding contacts in a map with relation to Account ID 
Map<String, Contact> mapContact = new Map<String, Contact>(); 
for(Contact cont : contactList) 
{ 
    mapContact.put(cont.Account.Id, cont) ; 
} 


// Updating Contact_ID__c from Map to new Account list to update 
List<Account> newAccounts = [select Id, Contact_ID__c from Account where Id in :newAccountIDList]; 

for(Account acct: newAccounts) 
{ 
**LINE 41** 
toUpdate.add(new Account(
    id = acct.Id, 
    Contact_ID__c = mapContact.get(acct.Id).Id 
)); 
} 

update toUpdate; 

} // if 
else if(trigger.isUpdate && trigger.new[0].Contact_ID__c == null && trigger.old[0].Contact_ID__c == null) 
{ 



List<String> newAccountIDList = new List<String>(); 


// Taking all account IDs in collection 
for(Account acct: Trigger.new) 
{ 
    newAccountIDList.add(acct.ID); 
} 

// Fetching contacts against the account IDs 
List<Contact> contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList];  


// Adding contacts in a map with relation to Account ID 
Map<String, Contact> mapContact = new Map<String, Contact>(); 
for(Contact cont : contactList) 
{ 
    mapContact.put(cont.Account.Id, cont) ; 
    } 


// Updating Contact_ID__c from Map to new Account list to update 
List<Account> newAccounts = [select Id, Contact_ID__c from Account where Id in :newAccountIDList]; 
// List<Account> toUpdate = new List<Account>(); 
for(Account acct: newAccounts) 
{ 

    toUpdate.add(new Account(
    id = acct.Id, 
    Contact_ID__c = mapContact.get(acct.Id).Id 
)); 
} 

update toUpdate; 

} // else if 

} // trigger 

回答

0

最有可能mapContact不包含價值的關鍵acct.IdmapContact.get(acct.Id)調用將返回null,以下.Id將給出空引用異常。

您應該在該行之前添加一個保護語句。例如。

if(mapContact.containsKey(acct.Id)) { 
    toUpdate.add(new Account(
     id = acct.Id, 
     Contact_ID__c = mapContact.get(acct.Id).Id 
    )); 
} 
相關問題