How to Create Sample Apex Trigger in SalesForce

Apex Trigger

Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in association with calls to the Force.com​ API.As a language Apex is an Integrated, easy to use, rigorous, multi-tenant aware, upgradeable, easy to test and versioned. Apex code can be initiated by Web service requests and from triggers on objects.

Apex is of generally two types:

  1. Schedulable Apex
  2. Batchable Apex


SCHEDULABLE:- There is an interface in apex which is schedulable




Schedulable {

Void executes (schedulable context sc)


Class time bomb implements schedulable {

Void executes (schedulable context SC) {

System.debug (‘ I love you Pandu’);

}             ↓

}              to perform DB operations here


Batch Apex operates over small batches of records, covering your entire record set and breaking the process down into manageable chunks.

  • The Interface used for batch apex is  database.batchable, where
  • The database is the class and
  • Batchable is the interface


An interface is nothing but a class in which the method signatures are present, but the body of the method is absent.Following are the methods of an interface:

  1. Start
  2. Execute
  3. Finish


Collect the data first

  • The return type is a query locator \ Iterable
  • Query Locator/I Iterable start (batchable context BC)


A group of values which we can apply is Iterable

Maximum  number of values → 50,000


It has a capacity of maximum 50 million records


As the data begin from the start and logic  here is performed on the data

  • Void executes (batch able content BC, list < S object >)


→ Void finish (batchable content DC)

→ Return type is void

  • The purpose of start method is to collect all the data that has to be processed it returns either an Iterable (or) query locator type, the former is used to work with a maximum limit of 50,000 records, whereas the latter is used up to a range of 50 million records. The output of ‘start’ goes as input to the ‘execute’ method
  • Execute method contains the business logic that has to be executed
  • After completing the process, the execute method  invokes the finish method , whose job is to send a notification to the  user after performing the task
  • Every method in an interface has a global level of visibility



Global class BA_ test implements data base < subject > database stateful


String one_name = ‘Krishna’;

Global iterable <subject> start (database batch able context bc)


List <book_c> BL = new list <book_c>();

One_name = ‘Ashok’;

BL = « ______ »;

CA → alias name to book_c)

Return bl;


Global void execute (database.batchable connext BC, list < book _ c > BL)


Since (book _ c b: BL )


System. Debug (‘book name:’ +b.name);


For (book_c  b: bl)


If (b. name ==’ chemistry’)


b. price = c = 200;

b. name = ‘physics’;

b. author = c = one_name;



Try {

Upset BL;


Catch (Dml Exception e ) {

Syatem.debug (‘unable to process books ‘);


For (book _c b:BL)


System.debug (‘book name:’ +b.name);



Global void finish (database.batch able content BC)


System.debug (‘updated chemistry books data is’);


Public static test method void main ()


BA_test bt = new BA_test ();

ID Jobid = database. executes batch (bt,50);



To execute batch apex we must create a test method

→ There is a special method database.executes batch, which takes two parameters

  • Instance (or) object of the class that implements the batchable interface
  • Number of records to be executed per batch

→ This method is called  inside the test method only


  • After finishing come back to the test method
  • To execute batch method returns the process ID, this ID can be used for  monitoring purposes.
  • By default a batch is stateless
  • Every batch apex is stateless, which means data members that are initialized at start, will not hold their values in execute and any way they do not reflect on finish method
  • Every method works in its own context
  • To execute the methods in a state full mechanism we implement an interface called database.state ful
  • There are no methods in the state ful interface


  • Triggers are database statements (or) actions which are free on the occurrence of an event over the database


Trigger trigger name on object name (trigger_events){



  • A trigger is Apex code that executes before or after specific manipulation language (DML) events occur, such as before object records are inserted into the database, or after records have been deleted
  • Triggers are stored as metadata in sales force
  • A list of triggers in your org is located at your name | setup | develop | apex trigger |
  • You can only create triggers from the associated object, not from that of apex triggers page

There are two types of triggers

  1. Before trigger
  2. After trigger
Before After
Insert Insert
Update Update
Delete Delete
  • DML statements → database (values)
  • Before years means before changing the values
  • After years means after changing the values
  • Check for a condition or error condition,
  • If this condition matches, roll back the statement and undo the effect
  • Triggers work in system mode
  • Apex triggers are viewing, checking & editing  only  and not for developing any trigger
  • Condition for a new trigger

→ Go to objects

→ Select object for which you are  going to create triggers

Ex:    student

→  Go to down the properties of student

→ Triggers —> New


The context variables provide runtime information about the trigger & the database, these variables are

1. Is executing:-

It returns true if the trigger is under execution , else false

2. Trigger. Is before:-

Returns true if this trigger has been fixed way before any record was saved

3. Trigger. Is after:-

Returns true if this trigger has been fixed after all records were saved

4. Trigger. is insert:-

Returns true if this trigger has been fixed due to an insert operation, available from the Sales force user interface, apex, or the API

5. Trigger. Is update:-

Returns true if this trigger was fixed due to an update operation, from the Sales force user interface, apex, or the API

6. Trigger. Is delete:-

Returns true if this trigger was fixed due to a delete operation, from the Sales force apex, or the API

7. Trigger. Is UN delete:-

Returns true if this trigger was fixed after a record is recovered from the recycle bin

8. Trigger. New:-

  • Reflects the new state of the database
  • Returns a list of the new versions of the subject records
  • Note that this S object list is only available in insert and update triggers, and the records can only be modified in ‘before triggers’

9. Trigger. OLD:-

  • Reflects the previous state of the database
  • Returns a list of  older versions of the subject records
  • Note that this S object list is only available in update and delete triggers

10. Trigger. New Map:-

  • A map of IDS to the new versions of the S object records
  • Note that this map is only available in ‘before the update’, ‘after insert’ and ‘after update’ triggers

11. Trigger. Old map:-

→ A map of IDS to the old versions of the S object records

→ Note that this map is only available in ‘update & delete’ triggers

  • Whichever trigger has been created first , it will work rapidly
  • There can be multiple triggers with similar events
  • For one trigger we have multiple conditions
  • What is the difference between the trigger.New and trigger.Old?

→ Trigger. New is holding your object record data which is being currently set by user and trigger. Old contains the history of object records


Trigger t1 on food_c (before insert) {

Last < food_c> fc = trigger. New ;

For (food_c f:fc)


If (f. price_c <300)


f. add error (‘do not eat too much’);





Trigger t1 on student_c (before insert, after insert, before update, after update) {

→ List < student_c> b= trigger. New

For (student_c  S : b) {

If  (S. name_c == ‘harishnath’) {

S. add error (‘do not allow this student’);




DML STATEMENTS:             


  • DML statements are not effected in the DB, these are only for testing in Apex classes by using test method
  • Inside a constructor , DML statements won’t execute
  • A DML statements are written below

Try {

} catch


  • Object oriented
  • Database operations : DML, SOQL and SOSL
  • Collections
  • Exceptions
  • Batch apex
  • Schedule apex
  • Triggers (monitoring DB operations )
  • Governor limits : above all runs against with G.L
  • Testing
  • Static
  • Integration

Enroll for Live Instructor Led Online SalesForce Training

0 Responses on How to Create Sample Apex Trigger in SalesForce"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.