Trigger scenarios in salesforce

In this Salesforce tutorial, we are going to learn about Trigger by creating simple triggers with examples and scenarios.

The following Trigger will fire when we try to create the account with the same name i.e Preventing the users to create Duplicate Accounts.

Trigger scenario 1:-

trigger AccountDuplicateTrigger on Account (before insert, before update)
 {
     for(Account a:Trigger.new) 
       {
           List<Account> acc=[Select id from Account where Name=:a.Name and Rating=:a.Rating ];
           if(acc.size()>0) 
          {
            acc.Name.addError('You Cannot Create the Duplicate Account'); 
          }
       }
 }

Trigger scenario 2:

The following trigger updates the field called “Hello” by the value “World”whenever we are creating an account or updating an account record. Create the field called “Hello” on the Account Object (Data Type = Text)

Trigger:

trigger HelloWorld on Account (before insert, before update) 
{
  List<Account> accs = Trigger.new;
  MyHelloWorld my= new MyHelloWorld(); //creating instance of apex class my.addHelloWorld(accs); // calling method from the apex class
}

Class:

public class MyHelloWorld 
{
public void addHelloWorld(List<Account> accs)
  {
  for (Account a:accs) 
   {
    if (a.Hello__c != 'World')
      {
       a.Hello__c = 'World'; 
      }
   } 
 }
}

Trigger scenario 3:

The following trigger describes about when the leads are inserted into the database it would add Doctor prefixed for all lead names. This is applicable for both inserting and updating the lead records.

trigger PrefixDoctor on Lead (before insert,before update) 
{
  List<Lead> leadList = trigger.new;
  for(Lead l: leadList) 
    {
      l.firstname = 'Dr.'+ l.firstname; 
    }
}

Trigger scenario 4

Create the object called “Books” and create field “Price”(data type is Currrency) under this object. Whenever we enter some amount of money in the Price field and once we click on save button, the value we entered in the Price field is 10% less than the actual price. This is applicable for while both inserting and updating records.

trigger DiscountTrigger on Book__c (before insert, before update) 
{
 List<Book__c> books = Trigger.new;   
 PriceDiscount.applyDiscount(books);
}

Class:

public class PriceDiscount 
{
  public static void applyDiscount(List<Book__c> books) 
   { 
    for (Book__c b :books)
      {
        b.Price__c *= 0.9;
      } 
   }
}

Trigger scenario 5

The following trigger creates the number of contacts which are equal to the number which we will enter in the Number of Locations field on the Account Object.

  • Create Custom field called “Number of Locations” on the Account Object (Data Type=Number)

Apex Trigger Code

trigger Prasanth on Account (after insert) 
{
list<contact> listContact = new list<contact>(); 
    map<id,decimal> mapAcc=new map<id,decimal>(); 
    for(Account acc:trigger.new){ 
        mapAcc.put(acc.id,acc.Number_of_Locations__c); 
}
    if(mapAcc.size()>0 && mapAcc!=null){ 
     for(Id accId:mapAcc.keyset()){
    for(integer i=0;i<mapAcc.get(accId);i++){ 
       contact newContact=new contact(); 
        newContact.accountid=accId; 
        newContact.lastname='contact'+i; 
        listContact.add(newContact); 
}   
  }

Apex Trigger Example

Trigger scenario 6

In this Salesforce Trigger scenario we are going to create a fields called “Sales Repr” with data type (Text) on the account Object. So what we are going to do in this trigger example 6.

When we create the Account record, the Account Owner will be automatically added to Sales Rep field. When we update the Account owner of the record, then also the Sales Rep will be automatically updated.

trigger UpdateSalesRep on Account (before insert, before update) 
{
    Set<Id>setAccOwner=new Set<Id>();
    for(Account Acc: trigger.new)
   { 
    setAccOwner.add(Acc.OwnerId);
    }
Map<Id,User>User_map = new Map<Id,User>([select Name from User where id in:setAccOwner]);
         for(Account Acc: Trigger.new)
         {
          User usr=User_map.get(Acc.OwnerId);
            Acc.Sales_Rep__c=usr.Name;
          }
}

Trigger Update Sales Rep field