Hurry! 20% Off Ends SoonRegister Now

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:

  • Schedulable Apex
  • Batchable Apex

Schedulable APEX:

Schedulable:- There is an interface in the apex which is schedulable

Limitations:

Eg:       

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

Batchable Apex:

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

  1. The Interface used for a batch apex is the database. batchable, where
  2. The database is the class and
  3. Batchable is the interface

MindMajix YouTube Channel

Methods In 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

Start:

Collect the data first

  1. The return type is a query locator Iterable
  2. Query Locator/I Iterable start (batchable context BC

Iterable:

A group of values that we can apply is Iterable

Maximum  number of values → 50,000

Quarry Locator:

It has a capacity of a maximum of 50 million records

Execute:

As the data begin from the start and logic  here is performed on the data
Void executes (batch able content BC, list < S object >)

Finish:

→ Void finish (batchable content DC)
→ The return type is void

  1. The purpose of the 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
  2. Execute method contains the business logic that has to be executed
  3. 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
  4. Every method in an interface has a global level of visibility

Ex:

Batch Apex:

Global class BA_ test implements data base < subject > database stateful
{
String one_name = ‘Krishna’;
Global iterable start (database batch able context bc)
{
List BL = new list ();
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);
}
Related Article: Salesforce Interview Questions and Answers

How To Execute Batchg Apex:

To execute batch apex we must create a test method
→ There is a special method database. executes batch, which takes two parameters

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

→ This method is called  inside the test method only

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

Triggers

  1. Triggers are database statements (or) actions that are free on the occurrence of an event over the database

Syntax:-                  

Trigger trigger name on object name (trigger_events){
Code_block
}
  1. 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
  2. Triggers are stored as metadata in salesforce
  3. A list of triggers in your org is located at your name | setup | develop | apex trigger |
  4. You can only create triggers from the associated object, not from that of the apex triggers page

There are two types of triggers

  • Before Trigger
  • After trigger

After
Insert      Insert
Update    Update
Delete     Delete
              Update

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

→ Go to objects
→ The select object for which you are  going to create triggers

Ex:    student

→  Go to down the properties of student
→ Triggers —> New

Related Article: SalesForce Tutorial for Beginners

Context Variables:

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 Salesforce user interface, Apex, or the API

5. Trigger. Is update: Returns true if this trigger was fixed due to an update operation, from the Salesforce user interface, Apex, or the API

6. Trigger. Is delete: Returns true if this trigger was fixed due to a delete operation, from the Salesforce 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:

  1. Reflects the new state of the database
  2. Returns a list of the new versions of the subject records
  3. 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:

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

10. Trigger. New Map:

  1. A map of IDS to the new versions of the S object records
  2. 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

  1. Whichever trigger has been created first, it will work rapidly
  2. There can be multiple triggers with similar events
  3. For one trigger we have multiple conditions
  4. 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

Eg:

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’);
}
}
}

Eg:

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 affected in the DB, these are only for testing in Apex classes by using test method
  • Inside a constructor, DML statements won’t execute
  • DML statements are written below
    Try {
    } catch

Features Of Apex:

  • 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

Related Articles:

An Overview of SalesForce Security

An Introduction to Visualforce – SalesForce

Access Specifiers in SalesForce Cloud Computing - Salesforce

Salesforce Platform Events

Mindmajix offers different Salesforce certification training according to your desire with hands-on experience on Salesforce concepts

Salesforce Administration TrainingSalesforce Lightning Training
Salesforce Advanced Developer TrainingSalesforce Developer Training
Salesforce IoT TrainingSalesforce App Builder Certification Training
Salesforce AppExchange TrainingSalesforce Service Cloud Training
and many more.. 

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Salesforce TrainingDec 24 to Jan 08View Details
Salesforce TrainingDec 28 to Jan 12View Details
Salesforce TrainingDec 31 to Jan 15View Details
Salesforce TrainingJan 04 to Jan 19View Details
Last updated: 04 Apr 2023
About Author

Arogyalokesh is a Technical Content Writer and manages content creation on various IT platforms at Mindmajix. He is dedicated to creating useful and engaging content on Salesforce, Blockchain, Docker, SQL Server, Tangle, Jira, and few other technologies. Get in touch with him on LinkedIn and Twitter.

read less
  1. Share:
Salesforce Articles