[SalesForce] Trigger on Tasks to change Lead Status

I'm trying to create a trigger on Leads that when the Lead Status = 'Open' and a Task is created for that records, as soon as the Task is saved (it doesn't matter if it is completed or still open) it will change the Lead Status to 'Contacted'.

You can't do it with workflows because it'll take it when the task is completed and only if the task has a due date.

This is what I've done so far:

trigger UpdateLeadswithTask on Task (after insert) {
    // set up lists you will need
    List<Lead> LeadsToUpdate = new List<Lead>();
    Map<Id, Task> taskMap = new Map<Id, Task>();

    // go through the list of tasks that were inserted
    for (Task t: Trigger.New)
    {
      // if they are related to a Lead, add the Lead id (whoID) and their values to a map
      if (t.WhatId  != null)
        {
            taskMap.put(t.WhatId, t);
        }
    }
    // if the map isnt empty
    if (taskMap.size() > 0)
    {
        // get all of the Leads related to the tasks
        LeadsToUpdate = [SELECT Id, Status FROM Lead WHERE Id IN: taskMap.keySet()];
        // go through the list for each Lead
        for (Lead l: LeadsToUpdate)
        { if (l.Status =='Working - Contacted')
            // set the new Lead status
            l.Status = 'Open - Not Contacted';
         else
             System.debug('The Status of the Lead was not Working - Contacted');
        }

        // if the list of Leads isnt empty, update them
        if (LeadsToUpdate.size() > 0)
        {
            update LeadsToUpdate;
        }
    }
}

It is not doing anything..I use the debug log and I don't see like it is doing anything (it is active). I also created a Test Class and it says the list is Null.

Best Answer

It's the "WhoId" not the "WhatId" that links to Leads. Change that in your code and you should be good.

Also it looks like you have your if statement backwards, changing Leads with Status of 'Contacted' to Status of 'Open'. Your question says to change from 'Open' to 'Contacted'

Related Topic