Advertisement
martyychang

trigger LaatsteCallMobileMiles on Task

Feb 22nd, 2014
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 qualyfing tasks, keyed on the Related To (WhatId)
  16.     // field on the task. This will be used later to pull in Task.CreatedDate
  17.     // when updating accounts
  18.  
  19.     Map<Id, Task> qualifyingTasksByWhatId = new Map<Id, Task>();
  20.  
  21.     // Go through the new tasks and check to see whether the task qualifies
  22.     // 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.  
  31.                 qualifyingTasksByWhatId.put(eachTask.WhatId, eachTask);
  32.             }
  33.         }   // if (eachTask.WhatId != null)
  34.     }   // for each Task in newTasks
  35.  
  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.     // 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.  
  46.     // Update any affected accounts
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement