So I'm trying to associate new contacts and cases with an account automatically. I've been creating contacts and cases without an account using an automated script. I understand that at this point, I have to use an APEX trigger although the use case is very simple.
I'm very new to APEX triggers, so I didn't get any further than the logic.
trigger associateWithAccount on Contact (before insert) {
//get Company__c from Contact
//lookup Accounts by Account Name using Company__c
//get AccountID from the result of that lookup
//insert AccountID from Account into AccountID in Contact
Map<String, String> extMap = new Map<String, String>();
Set<String> extIdSet = new Set<String>();
for(Contact c : Trigger.new){
extIdSet.add(c.Company__c);
}
for(Account a : [select Id, Name from Account where Name IN :extIdSet]){
extMap.put(a.Id, a.Name);
}
for(Contact c : Trigger.new){
c.Account = extMap.get(c.Id);
}
}
However, I keep getting the error that I am illegally assigning from String to Account. Any help?
Best Answer
Let's rewrite this with some better variable names while recognizing that Contacts if created from the UI will most likely have their AccountId already populated
And handy Util methods (there are other, better flavors of this like SObjectIndex in GitHub)