Wednesday , August 23 2017
Home / Apex / Apex Programming for beginners / Apex Trigger / Making the Apex trigger a bit more complex!!

Making the Apex trigger a bit more complex!!

Making the Apex trigger a bit more complex!!

 

Making a Call to class’s method from the Trigger.

 

This way we are able to implement the OOPs concept, our trigger’s code is efficient and maintenance of the code is easier.

 

In the following code, we are going to call a method from a utility class, this method is used for sending an email to a recipient.

 

To create the trigger, go to Developer Console->file->New-> Apex Trigger. Give it a name for e.g. SendEmailExampleTrigger and select Contact sObject.

 

You will get some predefined code in the console, replace it with this code and save it.

 

trigger SendEmailExampleTrigger on Contact (after insert, after delete) {

if (Trigger.isInsert) {

EmailManager.sendMail(SampleEmail@Address.com’, ‘Email’s Subject’,

‘Email’s Body’);

}

}

 

**** Email Manager utility class need to be created separately.

 

To test this trigger all we need to do is insert a contact record and we can see that the email is sent to the mentioned email in the code.

Adding Related records using Trigger

 

One of the main benefits of using triggers over workflow is to access any related records irrespective of the relationship they have, where as in workflow you can only make changes to the parent record.

 

In the below trigger, we are going to add a contact to account if there exists no contact information for the account. First, the trigger will make use of an SOQL query to find if there is any related contact and if it finds none then it will create a contact according to the business logic.

 

trigger AddRelatedContact on Account(after insert, after update) {

List<contact> contactList = new List< contact >();

Map<Id,Account> accountshavingContacts = new Map<Id,Account>(

[SELECT Id,(SELECT Id FROM contact) FROM Account WHERE Id IN: Trigger.New]);

// We have to loop through the map to fetch all the accounts with no contacts

for(Account acc : Trigger.New) {

if (accountshavingContacts.get(acc.Id).contacts.size() == 0) {

// Means there is no related contact for the account

contactList.add(new contact(lastName=acc.Name + ‘ triggercontact,

AccountId=a.Id));

}

}

 

if (contactList.size() > 0) {

insert contactList;

}

}

 

To test the Trigger create a sample account record and you will find that it will have an associated contact record.

About Sumit Datta

One comment

  1. you have a wonderful blog here! would you like to have invite posts on my own blog?

Leave a Reply

Your email address will not be published. Required fields are marked *