+ Start a Discussion
Patrick ConnerPatrick Conner 

Bulkify Code to Create Accounts on Contact Upserts

I'm trying to bulkify the following code, which works well for a single contact and parent account creation:
 
trigger createacc on Contact (after insert) {
list<Contact > con=[select id,lastname,email from contact where id in:Trigger.newMap.keySet()];
list<account >acc =new list<account>();
list<contact>cc1 =new list<contact>();
for(contact c : con)
{
account a =new account ();
a.name=c.lastname;
a.email__c=c.email;
acc.add(a);
}
insert acc;
for(account a1:acc){
system.debug('---------------------this is id --------------------'+a1.id);
for(contact c : con){
c.accountid=a1.id;
cc1.add(c);
}
}
update cc1;
}

Any help would be greatly appreciated! Thank you!
Best Answer chosen by Patrick Conner
Abhishek BansalAbhishek Bansal
Hi Patrick,

I would suggest you to create two triggers for this requirement.
First trigger will simply insert the account records when contacts are inserted :
trigger createacc on Contact (after insert) {
	List<Account> accList = new List<Account>();
	for(Contact con : trigger.new){
		Account acc = new Account();
		acc.name=c.lastname;
		acc.email__c=c.email;
		accList.add(acc);
	}
	if(accList.size() > 0){
		insert accList;
	}
}

Now second trigger will be written on Account which will update all the related contacts with account id :
trigger updateContact on Account (after insert){
	Set<String> setOfEmails = new Set<String>();
	for(Account acc : trigger.new){
		if(acc.Email__c != null){
			setOfEmails.add(acc.Email__c);
		}
	}
	
	Map<String,Contact> mapOfContacts = new Map<String,Contact>();
	for(Contact con : [Select AccountId,Email from Contact where Email IN :setOfEmails]){
		mapOfContacts.put(con.Email,con);
	}
	
	List<Contact> conToUpdateList = new List<Contact>();
	for(Account acc : trigger.new){
		if(mapOfContacts.containsKey(acc.Email__c)){
			mapOfContacts.get(acc.Email__c).AccountId = acc.id;
			conToUpdateList.add(mapOfContacts.get(acc.Email__c));
		}
	}
	if(conToUpdateList.size() > 0){
		update conToUpdateList;
	}
}

Please use both triggers for this requirement.
Let me know if you need more information on this.

Thanks,
Abhishek bansal