Apex Trigger Salesforce

Apex Trigger is an action which gets fired on particular event. In salesforce trigger is apex code that executes before or after the below types of operations.

– Insert

– Update

– Delete

– Undelete

Triggers will run before object records are inserted, updated, deleted into the database or after records are inserted, updated, deleted and restored.

Apex Triggers can be classified into two types:

1. Before triggers can be used to update or validate record values before they are saved to the database.

2. After triggers can be used to access field values that are set by the database, and to affect changes in other records.

Events in triggers:

Before Insert, Before Update, Before Delete

After Insert, After Update, After delete, After Undelete

Syntax to create sample trigger:

Use below syntax to create trigger.

	trigger <TriggerName> on ObjectName (<events>) {
		// you can write your code here.
	}

Now i will give simple example to under stand how trigger works.

Here i will give example, when account is inserted, automatically contact also created for that account. this example is to under stand how trigger works.

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

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.

Here in salesforce there many context variable available. Those are Trigger.New, Trigger.old, Trigger.NewMap, Trigger.OldMap, Trigger.isAfter, Trigger.isBefore, Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete and Trigger.isUndelete.

We will discuss about each and every context variable later.

Here one more thing i will tell. If you want to move your trigger to Production, you should cover at least 1% code coverage for trigger.

Comments