Search Here

Example of an After Trigger in Salesforce

 An after trigger is used to perform operations on records after they have been saved to the database. A common use case is updating related records or performing actions that require the record’s ID, which isn’t available until after the record is inserted.

Here’s an example:

trigger AccountAfterInsert on Account (after insert) {

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

        for (Account acc : Trigger.new) {

        // Create a new Contact for each Account inserted

        Contact newContact = new Contact();

        newContact.LastName = 'Primary Contact';

        newContact.AccountId = acc.Id; // Use the Account's ID

        contactsToCreate.add(newContact);

    }

        // Insert all new Contacts

    if (!contactsToCreate.isEmpty()) {

        insert contactsToCreate;

    }

}


Post a Comment

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