Apex Trigger Examples

  • AccountTrigger.apxt
trigger AccountTrigger on Account (after insert) {
    AccountTriggerHandler handler = new AccountTriggerHandler();
    switch on trigger.operationType {
        when AFTER_INSERT {
  • AccountTriggerHandler.apxc
public class AccountTriggerHandler {
    public void afterInsert(List<Account> accounts) {
        List<Contact> contacts = new List<Contact>();
        for (Account account : accounts) {
            Contact c = new Contact(LastName=account.Name,
        insert contacts;
  • AccountTrigger_Test.apxc
public class AccountTrigger_Test {
    static void TestBulkInsert() {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < 300; i++) {
            Account a = new Account(Name='Test');
        insert accounts;
    static void TestContactLinkingOnInsert() {
        Account a = new Account(Name='Test');
        insert a;
        List<Contact> c = [SELECT Id, AccountId
                             FROM Contact
                            WHERE (AccountId = :a.Id)];
        System.assert(c.size() >= 1);

3. Create a new Opportunity whenever an Account is created or updated for Industry of Agriculture:

4. Users should not be able to delete any Account with an associated Contact:

5. Only Admin can delete Closed Opportunities and an email should be sent to Owners for Closed Won Opportunities:

6. Write the count of total Contacts to their associated Account:

8. Whenever a new active User having profile System Administrator is inserted, add the user to the public group “Admins”:

9. Update example 8 such that whenever a User's profile is changed from or to System Administrator and the User is marked active or inactive, add or delete the user to the public group “Admins”: