2 Trigger Use Case

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Trigger Maintain Uniqueness (De-Duplication):

{
Criteria Events Context Variable
integer recordsCount = [select count() from Candidate__C
Fields are Mandatory Before Insert, Trigger.New where name =: cnd.name];
Update if(recordsCount > 0)
Auto populate Field Before Insert, Trigger.New {
Update
cnd.AddError('We have a Candidate Record with this
Prevent Deletion of Before Delete Trigger.Old
Name. Duplicate Candidates cannot be accepted.');
Active Record
}}}}
Maintain Uniqueness (De- Before Insert, Trigger.New
Duplication) Update Prevent Deletion of associated object Records:
Prevent Deletion of Before Delete Trigger.OldM
associated object Records ap.Keyset() {
Synchronize contact After Update Trigger.New List lstContacts = [Select id, firstname, lastname, accountid
record with associated Map.Keyset() from Contact where accountid IN : Trigger.OldMap.KeySet()];
account record if(! lstContacts.isEmpty())
trigger ContactDetails on Contact (before insert, before {
update) for(Contact con : lstContacts) { con.Accountid = null;
{ }
If ( (Trigger.isInsert || Trigger.isUpdate ) && update lstContacts; } } }
Trigger.isBefore)
{
for(Contact con : Trigger.New) Synchronize contact record with associated account record:
{ {
Fields are Mandatory: List lstAccounts = [select id, name, phone, fax, (Select id,
firstname, lastname, phone, fax from Contacts) from Account
if(con.Email == null || con.Email =='')
where ID in : Trigger.NewMap.keyset()];
{
List contactsToUpdate = new List(); if(! lstAccounts.isEmpty())
con.Email.AddError('Please Enter the Email Id value.');
{
}
for(Account acc : lstAccounts)
else if(con.Phone == null || con.Phone == '')
{
{
if(! acc.contacts.isEmpty())
con.Phone.AddError('Please Enter the Contact Number.');
{
}}}}
for(Contact con : acc.Contacts)
{
Auto populate Field: con.Phone = acc.Phone; con.Fax = acc.Fax;
contactsToUpdate.Add(con);
Switch on ld.industry
}}}}
{
if( ! contactsToUpdate.isEmpty())
When ‘Banking’
{
{
update contactsToUpdate;
Ld.record.AnnualRevenue=10000;
} }}}
{
Create a Trigger, to make sure Each Contact Should be get
Ld.record.AnnualRevenue=
associated with an Account.
When ‘Finance’
20000; trigger MakeContactAssociated on Contact (before insert,
}} Before Update)
{
Prevent Deletion of Active Record: if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isBefore)
{
{
for(Contact con : Trigger.New)
if(acc.Active__c == 'Yes')
{
{
if(con.AccountId == null )
acc.AddError('Your Are Not Authorized to Delete an
{
Active Account.'); } } } }
con.AddError('Please Make the Contact Should be associated
with an Account.'); } } } }
Autolead Conversion l.Email.addError('Email already exists');
} } } }
Create a Trigger, to AutoConvert the Lead Record upon
Q.7.Write a trigger to update a field (city) in Account when
changing the Lead Status to "Closed - Converted".
same field(city) is updated in opportunity
Object Name : Lead Event Name : After Update trigger AccountUpdate on Account (after update) {
trigger AutoLeadConversion on Lead (After Update) Set<id> AccountIds = new Set<id>();
{ for(Account a: trigger.new)
if(Trigger.isAfter && Trigger.isUpdate) {
{ if(a.city_c != trigger.oldmap.get(a.id).city_c){
// Get the Lead Record Status... AccountIds.add(a.id);
LeadStatus lStatus = [Select id, MasterLabel, isConverted
}}
from LeadStatus Where isConverted = true Limit 1];
List<opportunity> opport=[select id, City__c,Accountid from
// List to hold the Lead Records to Convert..
Opportunity where accountid in: Accountids];
List<Database.LeadConvert> lstLeadsToConvert = new
List<Database.LeadConvert>(); for(opportunity opp:opport)
for(Lead ld : Trigger.New) {
{ opp.City_c =
if(ld.Status == 'Closed - Converted' && ld.IsConverted == trigger.newmap.get(opp.accountid).city_c;
false) }
{ update opport;
Store the Lead Details into the LeadConvert Class.. }
Database.LeadConvert lConvert = new Q.When an opportunity is inserted or updated then if the
Database.LeadConvert(); stage name is ‘Closed won’ then add the task.
//Specify the Lead Id... trigger ClosedOpportunityTrigger on Opportunity (after insert,
lConvert.SetLeadID(ld.Id); after update) {
//Specify the Email Alert.. List<Task> taskList = new List<Task>();
lConvert.SetSendNotificationEmail(true); for (Opportunity o :[SELECT Id,StageName FROM
//Specify the option to generate Opportunity..
Opportunity WHERE StageName ='Closed Won' AND Id IN
lConvert.SetDoNotCreateOpportunity(ld.Do_Not_Cre
:Trigger.New])
ate_Opportunity__c);
{
//Specify the Lead Status...
lConvert.SetConvertedStatus(lStatus.MasterLabel); if(o.StageName == 'Closed Won')
//Add the Record to Collection to Convert Bulk Records.. {
lstLeadsToConvert.Add(lConvert); taskList.add(new task (Subject ='Follow Up Test Task' ,
}} WhatId=o.Id));
// Convert the Lead Records... }}
if(! lstLeadsToConvert.isEmpty()) if(taskList.size() > 0){
{ insert taskList;
Database.LeadConvertResult[] results = }}
Database.convertLead(lstLeadsToConvert); Q. Divide individual balance equally on contacts based on the
}}} total balance on related accounts whenever account is
updated
Q. When lead is created or updated then check if the email of Trigger calculateBalance on Account(after insert, after update)
lead is already there in existing contacts. If email already exist {
then throw error. List <Account> accList = [select id,name,Balance_c, (select
trigger DuplicateEmailsInLead on Lead (before insert, before id,name, IndividualBalancec from Contacts) from account
update) { where Balance_c > 0];
map<String,Contact> mapOfContact = new map<String, List <Contact> contactList = new List<Contact> ();
Contact>(); for(Account acc: accList)
list<Contact> con = [select id,email from contact]; {
for (contact c:con) if(acc.Contacts.size() >0){
{ Decimal storeAmount = acc.Balance__c/acc.Contacts.size();
mapofcontact.put(c.email,c); for(Contact cc:acc.Contacts)
} {
for(lead l : trigger.new) cc.IndividualBalance__c = storeAmount;
{ contactList.add(cc);
if((l.email != null) && (trigger.isInsert || (l.email != } }}
trigger.oldmap.get(l.id).email))){ update contactList;
if(mapofContact.containsKey(l.email)){ }
Q. Whenever new account is created with annual revenue trigger LeadScenario on Lead (before insert) {
more than 50,000 then add SALESFORCE as contact name. for(lead ld : trigger.new){
trigger annualRevenueAcc on Account(after insert){ if(ld.leadsource == ‘Local’)
List<Contact> cc = new list<Contact>(); {
for(Account acc:trigger.new) ld.Rating = 'Cold';
{ }
if(acc.AnnualRevenue > 50,000) else{
{ ld.Rating = 'Hot';
contact con = new contact(); }}}
con.FirstName ='Smriti';
con.lastName ='Sharan'; Use Case: Upon selecting Region, Region HR will automatically
con.accountid=acc.id; fetch. Session: 46 Custom Setting
cc.add(con);
trigger CustomerTrigger on Customer__c (before insert,
}}
before update)
insert cc;
{
}
if((trigger.isinsert && trigger.isupdate) && trigger.isbefore)
Q. Whenever account is created with industry as banking
{
then create a contact for account,contact lastname as
for(Customer__c cust : trigger.new)
account name and contact phone as account phone
{
Trigger industryAcc on Account(after insert){
if(cust.Region_Name__c != null && Region_Name__c !='')
List&lt;Contact&gt; cc = new List&lt;Contact&gt;();
{
for( Account acc: Trigger.new)
cust.Region_HR_Manager__c =
{
RegionDetail__c.GetValues(cust.Region_Name__c).Region_H
if(acc.Industry =='Banking')
R_Manager__c; } } }}
{
Contact c=new Contact();
What is a Recursive Trigger?
c.accountid = c.id; A recursive trigger is one that performs an action, such as
c.lastname = a.name; an update or insert, which invokes itself owing to, say
c.phone=a.phone; something like an update it performs.
cc.add(c); How to avoid Recursive Trigger:
To avoid recursive triggers you can create a class with a
}} static Boolean variable with default value true. In the
insert cc; trigger, before executing your code keep a check that the
} variable is true or not. Once you check make the variable
Q. Whenever case is created with origin as email then set false.
status as new and priority as Normal Example:
Ans: Trigger emailCase on Case(before insert){ Apex Code:
for(case c:trigger.new) public Class checkRecursive
{ {
if(c.origin =='Email') private static boolean run = true;
{ public static boolean runOnce()
c.status ='New'; {
c.priority ='Normal'; if(run)
} {
}} run=false; return true;
Scenario Based Interview }
1. Whenever a case is created with origin as ‘Phone’ then set Else
status as ‘New’ and Priority as ‘High’. {
Answer: Object: Case Trigger: Before insert return run;
trigger CaseOrigin on Case (before insert) { }}}
for(case c : trigger.new){ Trigger Code:
if(c.origin == 'Phone'){ trigger updateTrigger on anyObject(after update)
c.status = 'New'; {
c.priority = ’High’; if(checkRecursive.runOnce())
}}}
{
Q. Whenever Lead is created with LeadSource as Local then
//write your code here
give rating as cold otherwise hot.
}}
1. Is Test.startTest() and Test.stopTest() required in a test Answer: Scenario 1: If the two objects are new and there are
class? no records in each. Then we can create a Master-detail
Answer: Test.startTest() and Test.stopTest() exist primarily to relationship by creating the field in Setup.
allow you to reset the governor limits within the context of
your test execution and to be able to test asynchronous 7. If the two objects exist prior to this requirement and have
methods. These two statements cannot be called more than records . If this is the scenario then we should first create a
once within a testMethod. They are not required to be used lookup relationship between the two objects and make sure
but in some situations may be critical. that all the values are filled and then convert the relationship
to master-detail from lookup.
2. Let say a user does not have permission on a child object
and is having permission on parent object to 8. The requirement is to delete a set of records and don’t want
read/create/edit/delete parent object, If there is a trigger on them to be stored in the recycle bin as well. What are my
parent object to insert a child record after parent record is options?
created, will it create a child record or not after the user Answer: This can be done using the Hard Delete option. It can
insert parent record manually? be done in apex by calling emptyRecycleBin().
Answer: Yes, a child record will be created.
9. In the before Insert event trigger which context variable is
3. You are having a requirement to pass value from child correct Trigger.new or new Trigger.newmap?
component to parent component which type of event you Answer: As the event is before insert only trigger.new will be
will use? supported.
Answer: Component events are used in cases where there is a
relationship between two components. Component Events Trigger.newmap will not be supported as we do not have an id
are fired by the child components and handled by the parent of record before the record is inserted.
component.

4. Suppose we have a requirement to create an account using


a new button and some default values in the new account
screen. How can we achieve this requirement?
Answer: We can make use of force:createRecord; it is an event
that opens a page to create a record for a specific entity.

Sample syntax:
createRecord : function (component, event, helper) {
var createRecordEvent = $A.get("e.force:createRecord");
createRecordEvent.setParams({
"entityApiName": "ObjectApiName"
});
createRecordEvent.fire();
}

5. There is a profile by name ‘ReadAccessProfile’ and two


users User1 and User2 have been assigned to it. There is an
object X. I want to have ReadWrite access for User1 and
ReadOnly access for User2 for the object X. How can this be
accomplished?
Step 1: Read Access for both users is common hence in the
Profile settings give ‘Read’ access for the object ‘X’. By doing
this User U2 will be able to read all the records( One condition
satisfied) but User1 will only be able to read the records
(Second condition not satisfied).
Step 2: So next what we do is we create a permission set say
‘GrantWriteAccess’ and in this permission set we give the
object ‘X’ the Write access and assign the user User1 to this
permission set. (Second condition satisfied).
6. I have two objects Object1 and Object2 which are not
related to each other. Now I want to create a Master Detail
Relationship(MDR) between these objects. How can I do this?

You might also like