Territory Management 2.0
Territory2 および UserTerritory2Association の標準オブジェクトではトリガーがサポートされているため、これらのテリトリー管理レコードの変更に関連するアクションやプロセスを自動化できます。
Territory2 のサンプルトリガー
次のサンプルトリガーは、Territory2 のレコードが作成または削除されたときに実行されます。このサンプルトリガーでは、組織が Territory2Model オブジェクトに TerritoryCount__c というカスタム項目を定義して、各テリトリーモデルのテリトリーの正味の数を追跡します。テリトリーが作成または削除されるたびにトリガーコードの TerritoryCount__c 項目の値が増減します。
1trigger maintainTerritoryCount on Territory2 (after insert, after delete) {
2 // Track the effective delta for each model
3 Map<Id, Integer> modelMap = new Map<Id, Integer>();
4 for(Territory2 terr : (Trigger.isInsert ? Trigger.new : Trigger.old)) {
5 Integer offset = 0;
6 if(modelMap.containsKey(terr.territory2ModelId)) {
7 offset = modelMap.get(terr.territory2ModelId);
8 }
9 offset += (Trigger.isInsert ? 1 : -1);
10 modelMap.put(terr.territory2ModelId, offset);
11 }
12 // We have a custom field on Territory2Model called TerritoryCount__c
13 List<Territory2Model> models = [SELECT Id, TerritoryCount__c FROM
14 Territory2Model WHERE Id IN :modelMap.keySet()];
15 for(Territory2Model tm : models) {
16 // In case the field is not defined with a default of 0
17 if(tm.TerritoryCount__c == null) {
18 tm.TerritoryCount__c = 0;
19 }
20 tm.TerritoryCount__c += modelMap.get(tm.Id);
21 }
22 // Bulk update the field on all the impacted models
23 update(models);
24}UserTerritory2Association のサンプルトリガー
次のサンプルトリガーは、UserTerritory2Association のレコードが作成されたときに実行されます。このサンプルトリガーでは、ユーザーがテリトリーに追加されたことを知らせるメール通知が営業担当グループに送信されます。このトリガーは、ユーザーをテリトリーに追加したユーザーを特定します。さらに、追加された各ユーザー、そのユーザーが追加されたテリトリー、およびそのテリトリーが属するテリトリーモデルを特定します。
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];
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}