Search Here

Whenever a New Account Record is created then needs to generate an associated Contact Record automatically triggers in Salesforce

 To create a Contact automatically whenever a new Account is created, you can write an Apex Trigger in Salesforce. Here's how to implement this functionality:

trigger CreateContactOnAccountInsert on Account (after insert) {

    List<Contact> contactsToInsert = new List<Contact>();


    for (Account acc : Trigger.new) {

        // Create a Contact record associated with the Account

        contactsToInsert.add(new Contact(

            FirstName = 'Default',

            LastName = acc.Name, // Using Account Name as the Contact's Last Name

            AccountId = acc.Id // Linking Contact to the Account

        ));

    }


    // Insert all new Contacts in bulk

    if (!contactsToInsert.isEmpty()) {

        insert contactsToInsert;

    }

}

Explanation of the Code

  1. Trigger Event:

    • The trigger runs on the after insert event because we need the AccountId (generated only after the Account record is saved) to link the Contact to the Account.
  2. Logic:

    • For every Account in the Trigger.new list, a new Contact is created with:
      • A default FirstName (you can customize this).
      • LastName as the Account’s Name.
      • AccountId to associate the Contact with the Account.
  3. Bulk Handling:

    • All new Contact records are stored in a List<Contact> and inserted in bulk to ensure efficient processing in case of bulk Account creation.
@isTest
private class CreateContactOnAccountInsertTest {
    @isTest
    static void testCreateContactOnAccountInsert() {
        // Create a new Account
        Account testAccount = new Account(
            Name = 'Test Account'
        );
        insert testAccount;

        // Query for the associated Contact
        Contact associatedContact = [SELECT FirstName, LastName, AccountId FROM Contact WHERE AccountId = :testAccount.Id];
        
        // Assert that the Contact is created and associated with the Account
        System.assertEquals('Default', associatedContact.FirstName, 'First Name should be Default');
        System.assertEquals('Test Account', associatedContact.LastName, 'Last Name should match Account Name');
        System.assertEquals(testAccount.Id, associatedContact.AccountId, 'AccountId should match');
    }
}



Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.