36 Trigger Scenarios in Salesforce with Solution – Part 2

1. Write a trigger on contact to prevent duplicate records based on Contact Email & Contact Phone.

In this Trigger, we are using “before insert” and “before update” because during “Insert” and “Update” only we will be able to insert or make changes to the Email and Phone field. And we have to check whether it has a duplicate Email or Phone before it is getting inserted or updated, this is the reason why we are using “before”.

Before all of this, we have to think of possible ways of inputs and possible ways of outputs. There are 5 ways we can expect the input from the user, those are

  • If the Phone and Email are not mandatory fields then it should accept the null values.
  • If either one of the fields is null also it should accept the values.
  • If either one of the fields is duplicate then it should not accept the values.
  • If both the fields are duplicates then it should not accept the values.
  • And during updates, we should see that if we don’t change the values of Phone and Email still should be able to update.

Since we have the case where either one of the fields is duplicate it should not save, we need to write 2 maps Map<String ,Contact> where String contains the Email of the Contact which is either updating or inserting and Contact has its record. Another map Map<String, Contact> where String contains the Phone of the Contact which is either updating or inserting and Contact has its record. Then we will loop the Contacts which is getting inserted or updated, then if it is insertion happening then we no need to check its old data so we just put the data’s to the Map and when it comes to Updating as I told above we need to check if the Old Data of Email and Phone field is equal to the New Data of Email and Phone field. After checking that only we will be adding it to the Map separately.

After this, we are writing a query to get the List of Contacts whose Email and Phone are present on that Map. Then we are checking the Existing Contacts List is null or not. If not then we loop all the Existing Contact List and check if the Email is null, if not then we are getting that particular Email Contact from the Map and checking if that is null or not. If that is not null that simply means that Email already exists, so we are adding the “Email” word to display it on the error message. Then we are checking the same thing for the phone and if the Contact is present in the Map then we are checking if the error message variable is empty or not, if it is empty we are Adding “Phone” word to it else we are appending ” and Phone” word to it.

Now comes the end of the trigger, if the errorMessage variable is empty that means there are no duplicate records else it means that duplicate records are present. So if the errorMessage variable is not empty then we are displaying the Error Message.

2. Write a trigger, only the system admin user should be able to delete the task.

In this trigger, we are preventing deletion of task if other Users apart from System Administrator is trying to delete. So just by the word prevent we come to know that we should use the “before delete” trigger and check if the User trying to delete is System Administrator or not.

Before we start to write the trigger check if there is another user whose profile is not System Administrator. To check the Users Go to Setup-> then in Quick Find search Users now you can see the Users. If there is no User with another profile Create one by clicking on New User.

After your are done with the above thing, check if you have a login link next to the user for easy login. If not Go to Setup-> then in Quick Find search for “Login Access Policies” -> then Enable “Administrators Can Log in as Any User”, now go back to Users you we are able to see a Login link.

Now Create a new Task by Clicking on App Launcher and searching for Task and New, for the User which you just created or the User you already have who does not have a Profile as System Administrator.

Now we are ready to write the Trigger and Test it. Let’s get to the explanation of what is written in the Trigger, first, we are getting the Profile Id of the User who is trying to Delete the Task using the “Userinfo.getProfileId()” method. Then we are getting the Name of the Profile bypassing the Id of the Profile in the Query. Now we loop all the Tasks which are about to get deleted check if the Profile Name which we got from Query is System Administrator or not, if not we are displaying the Error Message.

After Done with writing the Trigger login to the other user and opening Tasks from App Launcher check for the task you just created in Today’s Task and try deleting that task you should get an Error Message.

 

3. Create a duplicate lead when a lead is inserted.

First, we need to create a Class to check Recursive. First, we declare a Boolean variable run with a value true to change its value after it has run once, then call a method to check if it has run once. If the method has run once then we set the run variable as false and return true if not we are returning false.

Now we are writing this trigger on “after insert” because after insertion only a duplicate record is created. In this what we should concentrate is once the insertion is happening then we are cloning the lead which is nothing but insertion so there are chances of Trigger running again this is why we have used checkRecursive Class. In this method, once the leads are inserted it will go the checkRecursive class run the runOnce method which default returns true, later we are cloning the lead that is nothing but again we are inserting the leads this time when it runs the runOnce method the value of a run is already false so the cloning doesn’t happen it will just finish running the Trigger.

 

4. Upload any pdf file into Document first. Send an email as an attachment to the lead email Id when a lead is created.
Email Subject: Welcome
Body: Please find the attached PDF.

In the above, as it is given we have to send the Email with Pdf File attached in it to the lead Email After it is created, so we have to use “after insert” Trigger.

Before writing a Trigger the first thing we need to do is Create a Email Template and attach a pdf file to be sent along with the Mail. To do that the Instruction are given in the Code in Comment Lines. After that we are getting the Email Template which we just created through query. Now we loop all the leads which is getting inserted and check if the Email field is null or not, if Email field is present then we are going to send the email so we will declare SingleEmailMessage the assign the things which are needed and mainly we have to set the TemplateId which we got in the query then add the toAddress as Lead Email and add the mail to the List of SingleEmailMessage . Later we will check if the List of Email is Empty or not, if not empty then we will be sending the Mail to the Lead Email.

 

5. Write a trigger on Contact, when contact is inserted an email should be sent to the contact email id with a specified template. So first you need to create a text template. The template Design is below.

Subject: A new Contact was Created.
Body :     Dear “Contact Name”,
A new contact was created with Name: “Contact Name” on “Contact CreatedDate”. Contact your System Administrator if it was not created by you.

Thank You
Regards System Administrator.

Here the Question is same as the previous message just that we need not attach any document. So here we will be creating the Classic Email Template. That is Go to Setup-> then search for “Classic Email Template”-> choose “Text” for “Choose the type of email template you would like to create.” ->then write the Subject=”A new Contact was Created.”, Email Template Name=”Email Template to send After Contact is Inserted” and write the Body as given above and if you want to insert the Contact Name then select “Contact Fields” from “Select Field Type” and select the field you want to insert in the “Select Field” and the field name will appear in “Copy Merge Field Value” field copy paste this in the body.

Now as we are ready with the Email Template we will do the same thing as we have done in the previous question.

 

6. When an opportunity line item is created an email should go to Opportunity Account Client Contact — Client Contact would be a field on Account lookup to contact.

Email Template: Hi, Contact Name
Your Order has been proceeding.
The order detail is below.
Product Name: “Product Name”
Product Code: “Product Code”
Unit Price: “Unit Price”
List Price: “List Price”

Thanks
User First Name User Last Name

We will be using “after insert” because the mail has to be sent after the Opportunity Line Item is created. After this check whether there is a Field with the Name “Client Contact” on Account with datatype “Lookup Relationship” if not create a new field on Account with the name “Client Contact” and data type “Lookup Relationship”.

As per the question we need to send the Mail to Opportunity’s Account’s ClientContact’s Email, so now we need the User Name and Opportunity Id of all the inserting OpportunityLineItem (Reminder: we also call OpportunityLineItem as Opportunity Product i.e, Products related tab in Opportunity Page Layout). From Opportunity Id, we can get the ClientContact’s Email by the Query which I have written in the code. We are going to add Opportunity Id and the complete details got from a query in one Map<Id, Opportunity> by looping all the Opportunities which we got from the query. Now we will loop the newly inserting OpportunityLineItem and check if the Opportunity Id is present in Map if yes then we will send a mail before declaring the SingleEmailMessage we need to see if the Contact Email is present then only we should send the mail, so we are checking for it and writing the Subject and Body and all in the code itself without creating an Email Template. This is also another way how you can write the Subject, Body in the code itself without creating an Email Template. After that, we are adding each SingleEmailMessage to the List of SingleEmailMessage and check if it is empty, if not we are sending the Email.

Now if you want to check the work you need Create an Opportunity Product that is You need to open the Opportunity Tab from App Launcher select any one Opportunity then you can see Products in the related tab there u will create a new Product. Before doing this click on Opportunities Account Name then go to its detail page Click on Client Contact and check if the is Email field is not null if it is null then try Entering your Email Id and check if you would get Mail.

Looking for part 3? – Trigger Scenarios Solution Part 3

If you didn’t go through the 36 Apex Triggers Scenarios in Salesforce Post Make sure to visit over there to check out the Trigger Scenarios
36 Trigger Scenarios in Salesforce

If you feel the solution can be optimized further please reach out to us.

Spread the love

Related Posts

2 thoughts on “36 Trigger Scenarios in Salesforce with Solution – Part 2

Leave a Reply

Your email address will not be published.

Archives

Recent Posts

×