Trigger examples and Scenarios
The following Trigger will fires when we try to create the account with same name i.e Preventing the users to create Duplicate Accounts.
Example 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'); } } }
Example 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'; } } } }
Example 3:
The following trigger describes about when the leads are inserted into the data base 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; } }
Example: 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; } } }