Experience Salesforce

When to use triggers

What You’ll Learn

  • When To Use Triggers In Apex?

When to Use Apex Triggers in Salesforce?

The changes that can be made using Apex Triggers in Salesforce include operations like Insert, Update, Delete, Merge, Upsert, and Undelete. Here are a few ways in which you can use apex trigger framework:

  1. If any change happens to single or multiple records, the Apex Trigger created on that object will be fired. For example, we can have a trigger run:
    1. Before an object’s record is inserted into the database.
    2. After a record has been deleted.
    3. Even after a record is restored back from the recycle bin.
  2. Triggers can be used to perform tasks that can’t be done using a point-and-click tool in Salesforce. If the task is possible using point & click tools then it is best to always prefer doing it from them.
  3. Triggers are active by default when created and Salesforce automatically fires active triggers when a specified database event occurs.

How to Create an Apex Trigger in Salesforce?

Apex allows you to define triggers for top-level standard objects that support triggers, one such Apex trigger use case is Contact or an Account. It can also be applied to some standard child objects, such as a CaseComment, and custom objects.

It is best to use a sandbox or a developer edition org to create triggers. This helps in avoiding any complications with your Salesforce database.

To create an Apex Trigger in Salesforce:

  1. Click on the “Setup” icon.
  2. Find the “Developer Console” and click on “Open link in New Tab”.
  3. Open a new file here and select “Apex Trigger”.
  4. Add “Name” of the Trigger and select “Object.”
  5. Click “Submit.” 
  6. You can see the syntax here and you can replace the default code with your “apex trigger code”.
  7. Create an Account and check if the trigger is working or not. If it creates an account, then the trigger is working.

Apex Trigger Use Cases Examples

  1. Creating Related Records: When a new Account is created, automatically create a related Contact.
trigger createCon_FromAcc on Account (after insert) {
    // initializing a List of sObject i.e. “Contact”
    List<Contact> con = new List<Contact>();

        // Creating and associating contact to each triggered Account.
    for(Account acc : Trigger.new){
        Contact c = new Contact();
        c.FirstName = ‘Sample ‘;
        c.LastName = acc.Name;
        c.AccountId = acc.Id;

        con.add(c);
    }        // performing DML operation to insert contact.
    insert con;
}
  1. Updating Related Records: If the owner of an Account is changed, update the owner for all related Contacts.
trigger UpdateContactOwner on Account(after update){
    // List to hold contacts to update
    List<Contact> con = new List<Contact>();

    // Iterate over the updated accounts
    for(Account acc : Trigger.new){
        // Check if the Account owner has changed
        if(acc.OwnerId != Trigger.oldMap.get(acc.Id).OwnerId){
            // Query related contacts
            List<Contact> relatedContacts = [select Id, OwnerId from Contact where AccountId = :acc.Id];

           // Update owner of related contacts
            for(Contact c : relatedContacts){
                c.OwnerId = acc.OwnerId;
                con.add(c);
            }
        }
    } 
   // Update the contacts in the database
    if(!con.isEmpty()){
        update con;
    }
}
  1. Opportunity Management: Create a new Opportunity whenever an Account is created or updated.
trigger createopportunity on Account(after insert, after update){
    // List to hold new opportunities
    List<Opportunity> opp = new List<Opportunity>();

        // Iterate over the updated or inserted accounts
    for(Account acc : Trigger.new){
        // Create a new Opportunity record
        Opportunity newOpp = new Opportunity();


        newOpp.Name = ‘Opportunity for ‘ + acc.Name;
        newOpp.AccountId = acc.Id;
        newOpp.StageName = ‘Prospecting’;

        // Opportunity close date will be, +1 month from today
        newOpp.CloseDate = System.today().addMonths(1);
                 // Add the opportunity to the list
        opp.add(newOpp);
    }
        // Insert the opportunities in the database
    if(!opp.isEmpty()){
        insert opp;
    }
}
  1. Data Integrity: Ensure all new Account records have a valid phone number before insertion.
trigger validPhone on Account (before insert) {
    // Iterate over the accounts being inserted
    System.debug(‘Triggered’);
    for(Account acc : Trigger.new){

         // Check if the phone number is empty or does not match a basic phone number pattern
        if (String.isEmpty(acc.Phone) || Pattern.matches(‘^\\d{10}$’, acc.Phone)) {

                // Add an error to the Phone field of the record
            acc.Phone.addError(‘Please provide a valid phone number.’);
            System.debug(‘Not valid number.’);
        }
    }
}
  1. Preventing Deletions: Prevent deletion of an Account if it has associated Contacts.
trigger preventAccDeletion on Account(before delete){
    set<ID> accId = new set<ID>();
    // Query to find Accounts that have related Contacts
    for (Account acc : [SELECT Id FROM Account WHERE Id IN :Trigger.old]) {
    // Count number of contacts associated with each account
    Integer conCount = [SELECT COUNT() FROM Contact WHERE AccountId = :acc.Id];

                // check if number of contacts greater than 0
        if(conCount > 0){
            accId.add(acc.Id);
        }
    }

      // Prevent deletion for Accounts that have associated Contacts
    for(Account acc : Trigger.old){
        if(accId.contains(acc.Id)){
            acc.addError(‘Cannot delete this Account because it has associated Contacts.’);
        }
    }
}
salesforce-developer
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale