1trigger notifySalesOps on UserTerritory2Association (after insert) {
2 // Query the details of the users and territories involved
3 List<UserTerritory2Association> utaList = [SELECT Id, User.FirstName, User.LastName,
4 Territory2.Name, Territory2.Territory2Model.Name
5 FROM UserTerritory2Association WHERE Id IN :Trigger.New WITH USER_MODE];
6
7 // Email message to send
8 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
9 mail.setToAddresses(new String[]{'salesOps@acme.com'});
10 mail.setSubject('Users added to territories notification');
11
12 // Build the message body
13 List<String> msgBody = new List<String>();
14 String addedToTerrStr = '{0}, {1} added to territory {2} in model {3} \n';
15 msgBody.add('The following users were added to territories by ' +
16 UserInfo.getFirstName() + ', ' + UserInfo.getLastName() + '\n');
17 for(UserTerritory2Association uta : utaList) {
18 msgBody.add(String.format(addedToTerrStr,
19 new String[]{uta.User.FirstName, uta.User.LastName,
20 uta.Territory2.Name, uta.Territory2.Territory2Model.Name}));
21 }
22
23 // Set the message body and send the email
24 mail.setPlainTextBody(String.join(msgBody,''));
25 Messaging.sendEmail(new Messaging.Email[] { mail });
26}