Tag Archives: Trigger

Difference between trigger and workflow rule

Workflow Rules:

  • Workflow is an automated process that fired after an action, based on evaluation criteria and rule criteria.
  • Workflow actions are Field Update, Email alert, Task alert and outbound message.
  • Workflow will be helpful to update the same object or master object in custom master-detail relationships.
  • We cannot fire workflows after record has been deleted.
  • We cannot query from database on workflow.


  • Trigger is a piece of code that executes before or after, when an DML event occurs like insert, update or Delete.
  • Trigger executes before or after these types of operations insert, update, delete, merge, upsert & undelete.
  • We can access the trigger across the object and related to that objects.
  • We can use DML operations in one trigger.
  • We can use SOQL’s from data base in one trigger.

Validation rule in apex trigger

Salesforce provides validation rules in configuration for standard and custom objects. sometimes the requirements may not be fulfilled using validation rule, especially when the validation criteria is very complex or need querying in database to check previously created data. In such a case we can write validation logic in trigger.

In this article, I will demonstrate how to write validation logic in apex trigger.

Here in below example, there is before insert and before update trigger on Opportunity object. In this trigger the amount field has validated, for less than 5000.

trigger TriggerOpportunity on Opportunity (before insert, before update){
    for(Opportunity opp:trigger.new){
        if(opp.Amount < 5000){
            opp.Amount.adderror('Amount cannot be less than 5000.');


Salesforce Apex Trigger Variable Availability to Events

Trigger.new Trigger.newMap Trigger.Old Trigger.OldMap
Before Insert Yes No No No
Before Update Yes Yes Yes Yes
Before Delete No No Yes Yes
After Insert Yes Yes No No
After Update Yes Yes Yes Yes
After Delete No No Yes Yes
After Undelete Yes Yes No No

Create Chatter Post Using Apex in Salesforce

Sample Code:

//Create a text post
FeedItem fi = new FeedItem();
fi.ParentId = '0010I00002AbcMm'; //Record Id
fi.Body = 'Chatter post from apex';
insert fi;

//Create a link text post
FeedItem fi = new FeedItem();
fi.ParentId = '0010I00002AbcMm'; //Record Id
fi.Body = 'Chatter post from apex';
fi.LinkUrl = 'http://www.salesforce.com';
insert fi;