Simple Apex Triggers Examples

Unknown | 03:52 | 0 comments

In  this is post, I have given very simple examples for learning salesforce Apex Triggers concepts.
Apex Triggers saves lots of time involving in automating complex businuess process

Examples


  1. Use case 1:

  • when account is inserted, automatically contact also created for that account.

trigger insertContact on Account (after insert)
{
Contact cont = new Contact();
cont.LastName = Trigger.new[0].name;
cont.AccountId = Trigger.new[0].ID;
insert cont;
}

  • Explanation:

Above one is a simple trigger to insert contact when you create account. the text which is mentioned in green color is trigger name. And text which is mentioned in red color is event name.

Trigger.New is a context variable. which returns a list of new records of the sobjects which we are going to insert into the database.




  1. Use Case 2:

  • Create a trigger on opportunity that throws error if Amount is less than 5000

trigger op_trigger1 on Opportunity (Before Insert, Before Update)
{
    for(Opportunity a : Trigger.New)
{
    if(a.Amount < 5000)
   a.addError('Amount can not be less then 5k');
}
}
  • Explanation:

Above one is a simple trigger which fires if Opportunity values is less than 5000 k. This is trigger triggers every time when record is created and updated



  1. Use Case 3:

  • If a New record is created, Amount should not be less than 5k If an Existing record is being updated , Amount should not be less than 3k

trigger opp_trigger2 on Opportunity (Before Insert, Before Update)
{
   for(Opportunity a : Trigger.New)
{
   if(Trigger.isInsert && a.Amount < 5000)
   a.addError('Amount can not be less than 5k');
   else if(Trigger.isUpdate && a.Amount < 3000)
   a.addError('Amount can not be less than 3k');
    }
}



4. Use Case 4:

  • Create a contact record on New Opportunity Insert
trigger opp_trigger3 on Opportunity (After Insert)
{
    Contact c = new Contact();
   for(Opportunity o : Trigger.New)
{
   c.AccountID = o.AccountID;
   c.FirstName = 'Oppertunity';
   c.LastName = 'Owner';
   insert c;
   }
}






Category: , , , ,

handsonbook.blogspot.com

0 comments