Trigger – Create Contact when Account is created

Create contact with account is created - CodersBugs
Create contact with account is created - CodersBugs

Here is apex trigger for creating contact when new account record is get added.

				
					trigger AccountTrigger2 on Account(after insert) {

    if (trigger.isInsert && trigger.isAfter) {
        List < Contact > lstContact = new List < Contact > ();

        for (Account acc: trigger.new) {
            Contact con = new Contact();
            con.FirstName = 'Test Contact' + acc.Name;
            con.LastName = 'Test';
            con.AccountId = acc.Id;
            lstContact.add(con);
        }

        if (!lstContact.isEmpty()) {
            database.insert(lstContact);
        }
    }
}
				
			

Watch the video for clarity

Leave a Reply