Salesforce Triggers Interview Questions
Questions And Answers
Company Asked: SLK Experience: 3+ years.
1) When an Account is deleted, you can write a trigger in Salesforce to delete the associated Contacts.
Ans )
trigger DeleteContactsOnAccountDelete on Account (before delete) {
Set<Id> accountIds = new Set<Id>();
for (Account acc : Trigger.old) {
accountIds.add(acc.Id);
}
List<Contact> relatedContacts = [SELECT Id FROM Contact WHERE AccountId IN :accountIds];
delete relatedContacts;
}
Company Asked: Salesforce Experience: 3+ years.
2)When creating a contact, verify if an account with the same email address already exists. If it does, link them. If not, create a new account using the same email and then link them.
Ans)
trigger ContactLinkingTrigger on Contact (after insert) {
List<Contact> contactsToUpdate = new List<Contact>();
Set<String> contactEmails = new Set<String>();
for (Contact newContact : Trigger.new) {
contactEmails.add(newContact.Email);
}
Map<String, Account> emailToAccountMap = new Map<String, Account>();
for (Account existingAccount : [SELECT Id, Email FROM Account WHERE Email IN :contactEmails]) {
emailToAccountMap.put(existingAccount.Email, existingAccount);
}
for (Contact newContact : Trigger.new) {
if (emailToAccountMap.containsKey(newContact.Email)) {
newContact.Linked_Account__c = emailToAccountMap.get(newContact.Email).Id;
}
else {
// Create a new Account and link it
Account newAccount = new Account(Name = 'New Account', Email = newContact.Email);
insert newAccount;
newContact.Linked_Account__c = newAccount.Id;
}
contactsToUpdate.add(newContact);
}
update contactsToUpdate;
}
3)Write a trigger to create a task record when an Opportunity stage changes.
Ans)
trigger CreateTaskUponOppStageChange on Opportunity (after update) {
Set<Id> processOpp = new Set<Id>();
for (Opportunity op : Trigger.new) {
if (op.StageName != Trigger.oldMap.get(op.Id).StageName) {
processOpp.add(op.Id);
}
}
if (!processOpp.isEmpty()) {
List<Opportunity> opps = [SELECT Id, Name, OwnerId FROM Opportunity WHERE Id IN :processOpp];
List<Task> insertTasks = new List<Task>();
for (Opportunity op : opps) {
Task newTask = new Task(
Subject = 'Opportunity Stage Changed: [' + op.Name + ']',
ActivityDate = Date.today().addDays(1),
WhatId = op.Id,
OwnerId = op.OwnerId,
Status = 'Not Started'
);
insertTasks.add(newTask);
}
if (!insertTasks.isEmpty()) {
insert insertTasks;
}
}
}
Company Asked: Deloitte, IBM Experience: 3+ years.
4)Write a trigger to ensure that when the Account owner changes, the Contacts associated with that Account also have their owner updated.
Ans)
trigger UpdateContactOwners on Account (after update) {
Set<Id> accountIds = new Set<Id>();
for (Account updatedAccount : Trigger.new) {
if (updatedAccount.OwnerId != Trigger.oldMap.get(updatedAccount.Id).OwnerId) {
accountIds.add(updatedAccount.Id);
}
}
if (!accountIds.isEmpty()) {
List<Contact> contactsToUpdate = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds];
for (Contact contact : contactsToUpdate) {
contact.OwnerId = Trigger.newMap.get(contact.AccountId).OwnerId;
}
update contactsToUpdate;
}
}
Company Asked: TCS Experience: 3+ years.
5)Create a trigger that restricts the deletion of Case records exclusively to the system administrator.
Ans)
trigger OnlySysAdminCanDeleteCase on Case (before delete) {
set<Id>ProcessCase = new set<Id>();
for(Case c : Trigger.Old){
ProcessCase.add(c.Id);
}
if(ProcessCase.size()>0){
Id UID = userinfo.getUserId();
User U = [SELECT Id,Profile.Name FROM User WHERE Id=:UID];
if(U.Profile.Name != 'System Administrator'){
Trigger.Old[0].Id.addError('You Cannot delete');
}
}
}
Company Asked: Koch Experience: 3+ years.
6)Write a trigger to prevent account deletion in Salesforce when any associated cases exist.
Ans)
trigger PreventAccountDeleteIfCasesAssociatedWithIt on Account (before delete) {
Set<Id> accountIds = new Set<Id>();
for (Account account : Trigger.old) {
accountIds.add(account.Id);
}
if (!accountIds.isEmpty()) {
List<Account> accountsWithCases = [
SELECT Id FROM Account WHERE Id IN :accountIds AND (SELECT Id FROM Cases) != null
];
for (Account account : accountsWithCases) {
Trigger.oldMap.get(account.Id).addError('Cannot delete: Associated cases exist.');
}
}
}
Company Asked: TCS Experience: 3+ years.
7)Create a trigger so that Account records will have a field named 'Opportunity Amount', which will display the amount from the most recently created Opportunity linked to the account.
Ans)
trigger OpportunityAmountTrigger on Opportunity (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
accountIds.add(opp.AccountId);
}
List<Account> accountsToUpdate = [
SELECT Id,Opportunity_Amount__c,
(SELECT Id, Amount FROM Opportunities ORDER BY CreatedDate DESC LIMIT 1)
FROM Account
WHERE Id IN :accountIds
];
for (Account acc : accountsToUpdate) {
if (acc.Opportunities.size() > 0) {
acc.Opportunity_Amount__c = acc.Opportunities[0].Amount;
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
Company Asked: Salesforce Experience: 3+ years.
8)When an account is created or modified, and the 'CopyBillingToShipping' checkbox is selected, the billing address should be automatically copied to the shipping address field.
Ans)
trigger CopyBillingToShippingTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.CopyBillingToShipping__c) {
acc.ShippingStreet = acc.BillingStreet;
acc.ShippingCity = acc.BillingCity;
acc.ShippingState = acc.BillingState;
acc.ShippingPostalCode = acc.BillingPostalCode;
acc.ShippingCountry = acc.BillingCountry;
}
}
}
9)Upon creating or updating an account, if the industry field is not null and contains the value 'Studio', then the Rating should be set to 'Hot'.
Ans)
trigger IndustryToRatingTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.Industry != null && acc.Industry == 'Studio') {
acc.Rating = 'Hot';
}
}
}
Company Asked: OT Experience: 3+ years.
10)When the phone number in the Account is updated, the new number should be populated across all related Contacts in the primary contact field.
Ans)
trigger UpdateContactPhoneTrigger on Account (before update) {
Map<Id, String> accountPhoneMap = new Map<Id, String>();
for (Account acc : Trigger.new) {
if (Trigger.oldMap.containsKey(acc.Id) && acc.Phone != Trigger.oldMap.get(acc.Id).Phone) {
accountPhoneMap.put(acc.Id, acc.Phone);
}
}
List<Contact> contactsToUpdate = [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :accountPhoneMap.keySet()
];
for (Contact con : contactsToUpdate) {
con.Phone = accountPhoneMap.get(con.AccountId);
}
if (!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
}
Thank you for reading the article.
Jayanth A
Comments
Post a Comment