• LOGIN
  • No products in the cart.

How to Create Sample Apex Trigger in Salesforce?

Apex Trigger

Apex is a strongly typed, object-oriented programming language that approves builders to execute float and transaction manage statements on the Force.com platform server in affiliation with calls to the Force.com API. As a language Apex is integrated, convenient to use, rigorous, multi-tenant aware, upgradeable, effortless to check, and versioned. Apex Code can be initiated through Web carrier requests and from triggers on objects.

Apex is of typically 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 function DB operations right here

Batchable Apex:

Batch Apex operates over small batches of records, protecting your complete record set and breaking the manner down into manageable chunks.

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

Methods In Interface:

An interface is nothing but a type in which the approach signatures are present, however, the physique of the approach is absent. Following are the strategies of an interface:

  1. Start
  2. Execute
  3. Finish

Start:

Collect the statistics first

  1. The return kind is a question locator Iterable
  2. Query Locator/I Iterable begin (batchable context BC

Iterable:

A team of values that we can observe is Iterable

The maximum range of values → 50,000

Quarry Locator:

It has the ability to most of 50 million records

Execute:

As the records commence from the beginning and common sense  right here is carried out on the data

(batch able content BC, list S object >) Void runs

Finish:

→ Void end (batchable content material DC)

→ The return kind is void

Also Read: Salesforce Integration Training

  1. The motive of begin approach is to gather all the records that have to be processed it returns both an Iterable (or) question locator type, the former is used to work with a most restricted of 50,000 records, whereas the latter is used up to vary of 50 million records. The output of ‘start’ goes as entered to the ‘execute’ method
  2. Execute technique incorporates the enterprise good judgment that has to be executed
  3. After finishing the process, the execute approach  invokes the end method, whose job is to ship a notification to the  person after performing the task
  4. Every technique in an interface has an international stage of visibility

Ex:

Batch Apex:

Global class BA_ test implements database < subject > database stateful

{

String one_name = ‘Krishna’;

Start with a global iterable (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 context 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 ) {

System.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);

}

How To Execute Batchg Apex:

To execute batch apex we ought to create a check method

→ There is an exclusive approach database. executes batch, which takes two parameters

  1. Instance (or) object of the type that implements the batchable interface
  2. Number of files to be done per batch

→ This technique is referred to as  interior the take a look at approach only

  1. After ending come lower back to the check method
  2. To execute the batch technique returns the manner ID, this ID can be used for monitoring purposes.
  3. By default a batch is stateless
  4. Every batch apex is stateless, which capacity records individuals that are initialized at the start, will no longer preserve their values in execute and anyway they do no longer replicate on end method
  5. Every approach works in its very own context
  6. To execute the techniques in a kingdom full mechanism we put into effect an interface known as a database. kingdom ful
  7. There are no techniques in the stateful interface

Triggers

Triggers are database statements (or) moves that are free on the incidence of a match over the database

Syntax:-

Trigger trigger name on object name (trigger_events){

Code_block

}

  1. A set-off is Apex code that executes earlier than or after particular manipulation language (DML) occasions occur, such as earlier than object documents are inserted into the database, or after archives have been deleted
  2. Triggers are saved as metadata in salesforce
  3. A listing of triggers in your org is positioned at your identify | setup | increase | apex set off |
  4. You can solely create triggers from the related object, now not from that of the apex triggers page

There are two kinds of triggers

  • Before trigger
  • After trigger

After

Insert       Insert

Update    Update

Delete     Delete

  Update

  1. DML statements → database (values)
  2. Before years capacity earlier than altering the values
  3. After years of skill after altering the values
  4. Check for a situation or error condition,
  5. If this situation matches, roll again the announcement and undo the effect
  6. Triggers work in gadget mode
  7. Apex triggers are viewing, checking & enhancing  solely  and now not for growing any trigger
  8. Condition for a new trigger

→ Go to objects

→ The pick out object for which you are  going to create triggers

Ex:    student

→  Go to down the residences of student

→ Triggers —&gt; New

Checkout Salesforce Tutorial

Context Variables:

The context variables supply runtime records about the set of &amp; the database, these variables are

  1. Is executing: It returns authentic if the set-off is underneath execution, else false
  2. Trigger. Is before: Returns genuine if this set-off has been constant way earlier than any file used to be saved
  3. Trigger. Is after: Returns authentic if this set-off has been constant after all archives have been saved
  4. Trigger. is insert: Returns actual if this set-off has been constant due to an insert operation, accessible from the Salesforce person interface, Apex, or the API
  5. Trigger. Is update: Returns authentic if this set off used to be constant due to a replace operation, from the Salesforce consumer interface, Apex, or the API
  6. Trigger. Is delete: Returns proper if this set off used to be constant due to a delete operation, from the Salesforce apex, or the API
  7. Trigger. Is UN delete: Returns real if this set off used to be constant after a document is recovered from the recycle bin
  8. Trigger. New:
    • Reflects the new country of the database
    • Returns a listing of the new variations of the challenge records
    • Note that this S object listing is solely accessible in insert and replace triggers, and the documents can solely be modified in ‘before triggers’
  9. Trigger. OLD:-
    • Reflects the preceding kingdom of the database
    • Returns a listing of  older variations of the situation records
    • Note that this S object listing is solely on hand in replace and delete triggers
  10. Trigger. New Map:-
    • A map of IDS to the new variations of the S object records
    • Note that this map is solely reachable in ‘before the update’, ‘after insert’, and ‘after update’ triggers
  11. Trigger. Old map:-
    • → A map of IDS to the historic variations of the S object records
    • → Note that this map is solely handy in ‘update & delete’ triggers
      1. Whichever set-off has been created first, it will work rapidly
      2. There can be a couple of triggers with comparable events
      3. For one set off, we have more than one conditions
      4. What is the distinction between the trigger? New and trigger. Old?

→ Trigger. New is keeping your object report information which is being presently set by using consumer and trigger. Old includes the records 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 an error (‘this student is not permitted ‘);

}

}

}

Dml Statements:

  • DML statements are now not affected in the DB, these are solely for trying out in Apex training using the usage of the check method
  • Inside a constructor, DML statements won’t execute
  • DML statements are written below

Try {

} catch

Best Salesforce Interview Questions and Answers

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 in opposition to G.L
  • Testing
  • Static
  • Integration

Conclusion

Salesforce has had great growth in terms of workers, clients, and offices throughout the world by providing creative and best-in-class ideas/solutions to solve today’s business problems.

GoLogica Technologies Private Limited  © 2019. All rights reserved.