function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nirdesh_BhattNirdesh_Bhatt 

Trigger on Contact which link Account from Account Name/Account ID

I have to Insert a Contact but before inserting a contact I have to check that related account is
there or not if the related account is there then insert a Contact with that account ID only else
insert an account and then insert a contact with that related account ID.     


Thanks,
Nirdesh Bhatt

 
KapilCKapilC
Hi Nirdesh,

Please find the code below.
 
trigger ContactTrigger on Contact (after insert) {
	map<id,account> contactIdAccountMap = new map<id,account>();
	for(Contact con : Trigger.New){
		if(con.AccountId == null){
			contactIdAccountMap.put(con.id, new account(Name= con.LastName));
		}
	}
	if(!contactIdAccountMap.isEmpty()){
		insert contactIdAccountMap.values();
		list<Contact> contactListToUpdate = new list<Contact>();
		
		for(Id key : contactIdAccountMap.keySet()){
			Contact conUpdate = new Contact(id=key,AccountId = contactIdAccountMap.get(key).id);
			contactListToUpdate.add(conUpdate);
		}
		if(!contactListToUpdate.isEmpty()){
			update contactListToUpdate;
		}
	}

}

[If you got answer from my post please mark it as solution.]


Thanks,
Kapil