Bulkified Contact Trigger That Creates An Account?
First off, you need to do this after insert since you need a contact Id to reference. Second, you should use DeveloperName
not Name
. Third, don't reference RecordType.Id
in the creation, instead use RecordTypeId
:
trigger CreateHouseholdAccount on Contact (after insert) {
RecordType arec = [SELECT ID FROM RecordType WHERE sObjectType = 'Account' AND DeveloperName = 'Household'];
Map<Id, Account> aMap = new Map<Id, Account>();
for (Contact con : trigger.new){
if(con.AccountID == null){
Account acc = new Account();
acc.name = con.FirstName + ' ' + con.LastName + ' ' + 'Household';
acc.RecordTypeId = arec.Id;
aMap.put(con.Id, acc);
}
}
if (!aMap.isEmpty()) {
insert aMap.values();
List<Contact> cList = new List<Contact>();
for (Id cId : aMap.keySet()) {
Contact con = new Contact();
con.Id = cId;
con.AccountId = aMap.get(cId).Id;
cList.add(con);
}
update cList;
}
}
Also we can use
List<RecordType> arecList = [SELECT ID FROM RecordType WHERE sObjectType = 'Account' AND DeveloperName = 'Household'];
and use arecList.get(0) in places of arec;
or use Try Catch method to execute SOQL.
We may never know when SOQL would fail.