I'm trying to create a trigger on Contacts that automatically creates and associates an Account if one has not been previously created. This was functionality that we had in a managed package that we had to uninstall. My initial effort was as follows.
trigger CreateHouseholdAccount on Contact (before insert) {
RecordType arec = SELECT ID FROM RecordType WHERE SobjectType = 'Account' AND Name = 'Household';
for (Contact c : trigger.new){
Account acc = new Account();
if(c.AccountID == null){
string cName = (c.FirstName + ' ' + c.LastName + ' ' + 'Household');
acc.name = cName;
acc.RecordType.id = arec.Id;
//fill in more account info based on contact
insert acc;
c.AccountID = acc.Id;
}
}
}
This code worked just fine but wasn't bulkified properly. A large upload of contacts would break the 50 DML action limit. This is where I'm having trouble. The following code is what I've come up with. It doesn't error out but also leaves the account field blank on the contact.
trigger Contact on Contact (before insert, before update) {
RecordType arec = [SELECT ID FROM RecordType WHERE SobjectType = 'Account' AND Name = 'Household'];
Map<Contact, Account> con_acc_map = new Map<Contact, Account>();
List<Account> list_acc = new List<Account>();
for (Contact c : trigger.new){
Account acc = new Account();
if(c.AccountID == null && c.LastModifiedById != '005G0000001cbVV' ){
string cName = (c.FirstName + ' ' + c.LastName + ' ' + 'Household');
acc.name = cName;
acc.BillingStreet = c.MailingStreet;
acc.RecordType.id = arec.Id;
con_acc_map.put(c, acc);
}
}
insert list_acc;
//update the contacts' account field
for (Contact c : trigger.new){
Account a = con_acc_map.get(c);
c.AccountId = a.id;
}
}
From what I can gather, con_acc_map
map is not updating the Account
objects with their ids from the insert operation. Is there anyway to do that or any alternative you can come up with? Thanks!