SHOW:
|
|
- or go back to the newest paste.
1 | /* | |
2 | * @see https://success.salesforce.com/answers?id=90630000000hdCVAAY | |
3 | */ | |
4 | trigger LaatsteCallMobileMiles on Task (after insert) { | |
5 | ||
6 | // Retrieve the email addresses of CreatedBy users for tasks currently | |
7 | // being processed by the trigger | |
8 | ||
9 | List<Task> newTasks = [ | |
10 | SELECT Id, WhatId, Subject, CreatedDate, CreatedBy.Email | |
11 | FROM Task | |
12 | WHERE Id IN :Trigger.new | |
13 | ]; | |
14 | ||
15 | - | // Initialize a map of accounts to update, based on the Related To |
15 | + | // Initialize a map of qualyfing tasks, keyed on the Related To (WhatId) |
16 | - | // (WhatId) field on the task. The map will be keyed on the Account ID, |
16 | + | // field on the task. This will be used later to pull in Task.CreatedDate |
17 | - | // to make sure the same account is not included twice in a single DML |
17 | + | // when updating accounts |
18 | - | // operation. |
18 | + | |
19 | Map<Id, Task> qualifyingTasksByWhatId = new Map<Id, Task>(); | |
20 | - | Map<Id, Account> affectedAccountsById = new Map<Id, Account>(); |
20 | + | |
21 | // Go through the new tasks and check to see whether the task qualifies | |
22 | - | // Go through the new tasks and check to see whether the account shoudl |
22 | + | // based on the email address and subject criteria |
23 | - | // be updated, based on the email address and subject criteria |
23 | + | |
24 | for (Task eachTask : newTasks) { | |
25 | if (eachTask.WhatId != null) { | |
26 | if (eachTask.CreatedBy.Email.contains('@mobilemiles.nl') | |
27 | && eachTask.Subject.contains('Made call to')) { | |
28 | ||
29 | // Put the qualifying task in the map | |
30 | - | // Construct the Account record to update |
30 | + | |
31 | qualifyingTasksByWhatId.put(eachTask.WhatId, eachTask); | |
32 | - | Account affectedAccount = new Account( |
32 | + | |
33 | - | Id = eachTask.WhatId, |
33 | + | |
34 | - | Laatste_activiteit_Mobile_Miles__c = eachTask.CreatedDate); |
34 | + | |
35 | ||
36 | - | // Put the affected account in the map |
36 | + | // Look for accounts that were affected, by querying the account object. |
37 | // This avoids situations where the task is not related to an account but | |
38 | - | affectedAccountsById.put(affectedAccount.Id, affectedAccount); |
38 | + | // to some other type of record in the system. |
39 | ||
40 | List<Account> affectedAccounts = [ | |
41 | SELECT Id | |
42 | FROM Account | |
43 | WHERE Id IN :qualifyingTasksByWhatId.keySet() | |
44 | ]; | |
45 | - | if (!affectedAccountsById.isEmpty()) |
45 | + | |
46 | - | update affectedAccountsById.values(); |
46 | + | |
47 | ||
48 | if (affectedAccounts.size() > 0) { | |
49 | for (Account eachAccount : affectedAccounts) { | |
50 | eachAccount.Laatste_activiteit_Mobile_Miles__c = | |
51 | qualifyingTasksByWhatId.get(eachAccount.Id).CreatedDate; | |
52 | } | |
53 | ||
54 | update affectedAccounts; | |
55 | } | |
56 | } |