Created
December 23, 2017 20:00
-
-
Save dsilvadeepal/80b987e24f9061cc15831ad91c601262 to your computer and use it in GitHub Desktop.
When a new opportunity is created, all contacts on the corresponding account need to have the following info added to their description: Opp creator's name , Opp close date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
When a new opportunity is created, all contacts on the corresponding account need to have | |
the following info added to their description: Opp creator's name , Opp close date | |
*/ | |
trigger AddOppInfoToContacts on Opportunity (after insert) { | |
for(Opportunity opp : Trigger.new) { | |
if(opp.AccountId != null) { | |
//Get all contacts we need to update | |
List<Contact> contacts = [SELECT Id, Description | |
FROM Contact | |
WHERE AccountId = :opp.AccountId]; | |
//Get opp creator info | |
User oppCreator = [SELECT Name | |
FROM User | |
WHERE Id = :opp.OwnerId]; | |
String oppInfo = 'New opportunity created by ' + | |
oppCreator.Name + ' with close date ' + | |
String.valueOf(opp.CloseDate) + '.'; | |
if(!contacts.isEmpty()) { | |
for(Contact con : contacts){ | |
String newContactDesc = oppInfo; | |
//Add the old description to the end if there already exists any description | |
if(con.Description != null){ | |
newContactDesc += '\n\n' + con.Description; | |
} | |
con.Description = newContactDesc; | |
} | |
update contacts; | |
} | |
} | |
} | |
} | |
//Test Class | |
@isTest | |
private class AddOppInfoToContactsTest { | |
@isTest static void createOppOnAccount(){ | |
Account acc = new Account(); | |
acc.Name = 'Windsor Hotels'; | |
insert acc; | |
List<Contact> contacts = new List<Contact>(); | |
for(Integer i = 0; i < 3; i++){ | |
String iString = String.valueOf(i); | |
Contact myCon = new Contact(); | |
myCon.LastName = iString; | |
myCon.AccountId = acc.Id; | |
myCon.Description = iString; | |
contacts.add(myCon); | |
} | |
insert contacts; | |
Opportunity opp = new Opportunity(); | |
opp.Name = 'Windsor Hotels Atlanta Deal'; | |
opp.StageName = 'Prospecting'; | |
opp.CloseDate = Date.today(); | |
opp.AccountId = acc.Id; | |
insert opp; | |
List<Contact> updatedContacts = [SELECT Description | |
FROM Contact | |
WHERE AccountId = :acc.Id]; | |
opp = [SELECT CreatedBy.Name, CloseDate | |
FROM Opportunity | |
WHERE Id = :opp.Id]; | |
for(Contact con : updatedContacts){ | |
System.assert(con.Description.contains(opp.CreatedBy.Name)); | |
System.assert(con.Description.contains(String.valueOf(opp.CloseDate))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment