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;

}

Company Asked: Deloitte                                                                                         Experience: 3+ years.

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;

        }

    }

}

Company Asked: Accenture                                                                                       Experience: 3+ years.

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;

   }

}

Company Asked: NTT DATA                                                                                   Experience: 3+ years.

11)When the Opportunity Stage field is modified, a Task record should be created within the Opportunity and assigned to the logged-in user ?

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.size() > 0) {
        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 = 'From Opportunity (Stage Changed): [' + op.Name + ']',
                ActivityDate = Date.today().addDays(1),
                WhatId = op.Id,
                OwnerId = UserInfo.getUserId(), 
                Status = 'Not Started'
            );
            insertTasks.add(newTask);
        }

        if (insertTasks.size() > 0) {
            insert insertTasks;
        }
    }
}


Company Asked: TCS                                                                                               Experience: 3+ years.

12)Create a trigger for the Account object that has a custom field named Total_Contacts_Count__c. This trigger should update the contacts count whenever a new contact is added, or an existing contact is deleted in relation to that account.

Ans)
 trigger UpdateContactCountOnAccount on Contact (after delete, after insert, after update, after undelete) {
    Set<Id> accountIds = new Set<Id>();

    if (Trigger.isInsert || Trigger.isUndelete) {
        for (Contact contact : Trigger.new) {
            accountIds.add(contact.AccountId);
        }
    } else if (Trigger.isUpdate || Trigger.isDelete) {
        for (Contact contact : Trigger.old) {
            accountIds.add(contact.AccountId);
        }
    }

    List<Account> accountsToUpdate = new List<Account>();
    for (Id accountId : accountIds) {
        Integer contactCount = [SELECT COUNT() FROM Contact WHERE AccountId = :accountId];
        accountsToUpdate.add(new Account(Id = accountId, Total_Contacts_Count__c = contactCount));
    }

    update accountsToUpdate;
}

Company Asked: DELL                                                                                            Experience: 3+ years.
13)If an account is created, generate 10 related contacts, and if an account is deleted, remove the associated contacts in Salesforce using a trigger?

Ans)
trigger AccountTrigger on Account (after insert, before delete) { if (Trigger.isAfter && Trigger.isInsert) { List<Contact> contactsToCreate = new List<Contact>(); for (Account acc : Trigger.new) { for (Integer i = 0; i < 10; i++) { Contact newContact = new Contact( FirstName = acc.Name + i, LastName = acc.Last_Name__c + i, AccountId = acc.Id ); contactsToCreate.add(newContact); } } if (!contactsToCreate.isEmpty()) { insert contactsToCreate; } } if (Trigger.isBefore && Trigger.isDelete) { List<Contact> contactsToDelete = [SELECT Id FROM Contact WHERE AccountId IN :Trigger.oldMap.keySet()]; if (!contactsToDelete.isEmpty()) { delete contactsToDelete; } } }


Feel free to post any comments regarding mistakes, corrections, ideas, and suggestions related to the article.

Thank you for reading the article.

Jayanth A


Comments

Popular posts from this blog

Salesforce Admin Notes

Salesforce Limitations

Salesforce Order of Execution