• Elliot32
  • NEWBIE
  • 20 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 2
    Replies
Thanks for taking a look at my trigger, the goal of the trigger is the following:

Whenever a Task where Type == 'Call' and Status == 'Completed' and the WhoId references to a Lead is either inserted, updated, deleted or undeleted, to take a Lead field called Last_Transfer_Date_Time__c (a datetime field) and pass it to the Task field Last_Transfer_Date_Time__c (datetime); the whole purpose of this is for the query. After this happens, I would like to sum up all Tasks that fit the afforementioned criteria, as well as a formula boolean field on the Task called Task_this_Cycle__c (this checks true when Activity_Date_Time__c [the datetime of the activity] is greater than Last_Transfer_Date_Time__c).

However, I am running into the too many queries error and having been banging my head against my keyboard for the past few days trying to resolve. My ultimate goal is to be able to roll-up all Tasks where Type == 'Call' and Status == 'Completed' where the Task was created after the Last Transfer Date Time of the Lead (in case my strategy is off base). Any help is much appreciated! Thanks, Elliot.
 
trigger EPS_CallsSinceTransfer_v3 on Task (after insert, after update, after delete, after undelete) {

    List<Id> leadIdList = new List<Id>();
    
    If (Trigger.isInsert || Trigger.isUndelete) {
        For (Task t : Trigger.new) {
            If (t.WhatId == null && t.WhoId != null && t.WhoId.getSObjectType() == Lead.SObjectType && t.Status == 'Completed' && t.Type == 'Call') {
                leadIdList.add(t.WhoId);
            }
        }
    }
    
    If (Trigger.isDelete || Trigger.isUpdate) {
        For (Task t : Trigger.old) {
            If (t.WhatId == null && t.WhoId != null && t.WhoId.getSObjectType() == Lead.SObjectType && t.Status == 'Completed' && t.Type == 'Call') {
                leadIdList.add(t.WhoId);
            }
        }
    }
    
    If (leadIdList.isEmpty() == false) {
    
        List<Lead> leadsWithTasks = [SELECT Id, Calls_this_Cycle__c, Last_Transfer_Date_Time__c FROM Lead WHERE Id IN : leadIdList];
        List<Lead> leadsToUpdate = new List<Lead>();
        List<Task> tasksToCount = new List<Task>();
        List<Task> tasksToUpdate = new List<Task>();
        
        For (Lead ld : leadsWithTasks) {
            
            For (Task t : [SELECT Id, Type, Status, Task_this_Cycle__c FROM Task WHERE Type = 'Call' AND Status = 'Completed' AND (WhoId IN : leadsWithTasks)]) {
            
                t.Last_Transfer_Date_Time__c = ld.Last_Transfer_Date_Time__c;
                tasksToUpdate.add(t);
            }           

            update tasksToUpdate;
            
            For (Task t : tasksToUpdate) {
                If (t.Task_this_Cycle__c == true) {
                    tasksToCount.add(t);
                }
            }
        
            ld.Calls_this_Cycle__c = tasksToCount.size();
            leadsToUpdate.add(ld);
        
        }
        
        If (leadsToUpdate.isEmpty() == false) {
            update leadsToUpdate;
        }
    }
}

 
Hello Forum,

Disclaimer: Apex novice.

I am having a slight issue with a Task Trigger. I am attempting to rollup the number of Tasks to a Lead record that fit the following criteria:
- Type = 'Call'
- Status = 'Completed'
- The Activity_Date_Time__c field (datetime) must be greater than the Lead.Last_Transfer_Date_Time__c field (datetime)

Please see the below code:
 
trigger EPS_CallsSinceTransfer_v3 on Task (after insert, after update, after delete, after undelete) {

    List<Id> leadIdList = new List<Id>();
    
    If (Trigger.isInsert || Trigger.isUndelete) {
        For (Task t : Trigger.new) {
            leadIdList.add(t.WhoId);
        }
    }
    
    If (Trigger.isDelete || Trigger.isUpdate) {
        For (Task t : Trigger.old) {
            leadIdList.add(t.WhoId);
        }
    }
    
    List<Lead> leadUpdateList = new List<Lead>();
    
    For (Lead led : [SELECT Id, Calls_this_Cycle__c, Last_Transfer_Date_Time__c, (SELECT Id, Activity_Date_Time__c FROM Tasks WHERE (Type = 'Call' AND Status = 'Completed') AND Activity_Date_Time__c >: Lead.Last_Transfer_Date_Time__c) FROM Lead WHERE Id =: leadIdList]) {
        led.Calls_this_Cycle__c = led.Tasks.size();
        leadUpdateList.add(led);
        update leadUpdateList;
    }
}

Each time I attempt to save the record I get the following error:

Error: Compile Error: Invalid bind expression type of Schema.SObjectField for column of type Datetime at line 19 column 203

Any ideas?

Thanks,
Elliot
Hi All,

Please see below Task Trigger (1st) and Test Class (2nd):
 
Trigger EPS_LeadStatusOppStageToTask on Task (before insert, before update) {
    
    String lead_prefix = Schema.SObjectType.Lead.getKeyPrefix();
    String opportunity_prefix = Schema.SObjectType.Opportunity.getKeyPrefix();
    
    Map<Id, List<Task>> whoWhatIds = new Map<Id, List<Task>>{};

    For (Task t : trigger.new) {
        
        If (Trigger.isUpdate) {
        
        Task oldTask=Trigger.oldMap.get(t.Id);
    
        Boolean oldTaskIsCompleted=oldTask.Status.equals('Completed');
        Boolean newTaskIsCompleted=t.Status.equals('Completed');
        
        If (t.WhatId == null && t.WhoId != null && ((String)t.WhoId).startsWith(lead_prefix) && (!oldTaskIsCompleted && newTaskIsCompleted)) {
            List<Task> tasks = whoWhatIds.get(t.WhoId);
            If (tasks == null) {
                tasks = new List<Task>{};
                whoWhatIds.put(t.WhoId, tasks);
                tasks.add(t);
            }
        } Else If (t.WhatId != null && ((String)t.WhatId).startsWith(opportunity_prefix) && (!oldTaskIsCompleted && newTaskIsCompleted)) {
            List<Task> tasks1 = whoWhatIds.get(t.WhatId);
            If (tasks1 == null) {
                tasks1 = new List<Task>{};
                whoWhatIds.put(t.WhatId, tasks1);
                tasks1.add(t);
            }
        }
        }
        
        If(Trigger.isInsert) {
        
        If (t.WhatId == null && t.WhoId != null && ((String)t.WhoId).startsWith(lead_prefix) && t.Status == 'Completed') {
            List<Task> tasks = whoWhatIds.get(t.WhoId);
            If (tasks == null) {
                tasks = new List<Task>{};
                whoWhatIds.put(t.WhoId, tasks);
                tasks.add(t);
            }
        } Else If (t.WhatId != null && ((String)t.WhatId).startsWith(opportunity_prefix) && t.Status == 'Completed') {
            List<Task> tasks1 = whoWhatIds.get(t.WhatId);
            If (tasks1 == null) {
                tasks1 = new List<Task>{};
                whoWhatIds.put(t.WhatId, tasks1);
                tasks1.add(t);
            }
        }
        }
    }

    For (Lead ld : [Select Id, Name, Status from lead where Id in :whoWhatIds.keySet()]) {
        For(Task t2 : whoWhatIds.get(ld.id)) {
            t2.Lead_Opp_Status_Stage__c = ld.Status;
        }
    }

    For(Opportunity opp : [Select Id, Name, StageName from Opportunity where Id in :whoWhatIds.keySet()]) {
        For(Task t3 : whoWhatIds.get(opp.id)) {
            t3.Lead_Opp_Status_Stage__c = opp.StageName;
        }
    }
}
 
@isTest
Public class EPS_Test_LeadStatusOppStageToTask {

    private static testMethod void myUnitTest() {
        
        Lead newLead = new Lead (
                       LastName = 'Test',
                       Company = 'Test Company',
                       Phone = '3759275838',
                       Industry = 'Arts',
                       Status = 'New'
                       );
        insert newLead;
        
        Account newAcct = new Account (
                          Name = 'Test Company'
                          );
        insert newAcct;
        
        Opportunity newOpp = new Opportunity (
                             Name = 'Test Company',
                             AccountId = newAcct.Id,
                             CloseDate = System.today(),
                             StageName = 'Demo Held'
                             );
        insert newOpp;
                             
        Task newTask = new Task (
                       WhatId = newOpp.Id,
                       Type = 'Call',
                       Status = 'Completed',
                       ActivityDate = date.today()
                       );
                       
        Task newTask1 = new Task (
                        WhoId = newLead.Id,
                        Type = 'Call',
                        Status = 'Completed',
                        ActivityDate = date.today()
                        );
                        
        Task newTask2 = new Task (
                        WhatId = newOpp.Id,
                        Type = 'Call',
                        Status = 'Not Started',
                        ActivityDate = date.today().addDays(5)
                        );
                       
        Task newTask3 = new Task (
                        WhoId = newLead.Id,
                        Type = 'Call',
                        Status = 'Not Started',
                        ActivityDate = date.today().addDays(5)
                        );
                       
        Test.startTest();
        
            insert newTask;
            System.assert(newTask.Lead_Opp_Status_Stage__c == 'New');
            
            insert newTask1;
            System.assert(newTask1.Lead_Opp_Status_Stage__c == 'Demo Held');
            
            insert newTask2;
            newTask2.Status = 'Completed';
            System.assert(newTask2.Lead_Opp_Status_Stage__c == 'New');
            
            insert newTask3;
            newTask3.Status = 'Completed';
            System.assert(newTask3.Lead_Opp_Status_Stage__c == 'Demo Held');
            
        Test.stopTest();
    }
}

The trigger works well enough for my purposes, but I cannot seem to get the code coverage above 56%. Also, when I run the Test, my Method does not Pass!

My question is this: Are there any resources available to help one identify where the test class is lacking in coverage on a particular trigger? ie Where in my trigger is the code not covered?

In addition, are there any particular recommendations for me here to improve coverage? I am a novice Apex developer so this is still a learning experience for me. If you would like to take the time on recommendations for me to improve my code as well, that would be appreciated; the trigger does in fact work, but I am sure there are more succinct ways to accomplish the same thing.

Thanks!
Elliot
Hi All,

Disclaimer: I am a beginner developer and am still working to understand Apex; I have strong Admin experience. Please see my code below:
 
trigger EPS_LeadCycleCreator on Lead(after update)
{
    List<Lead_Cycle__c> LeadCycles = new List<Lead_Cycle__c>();
    
    Set<Id> ownerIds = new Set<Id>();
    for(Lead l : trigger.new)
    {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        Boolean oldLeadIsInactive = oldLead.Trigger_Owner_Active__c == false;
        Boolean newLeadIsInactive = l.Trigger_Owner_Active__c == false;
        
        if((!oldLeadIsNo && newLeadIsNo) || (!oldLeadIsInactive && newLeadIsInactive))
        {
            ownerIds.add(l.OwnerId);
        }
    
    }
    
    Map<Id, User> ownerMap = new Map<Id, User>([ Select Id, ProfileId, Profile.Name From User where Id IN: ownerIDs ]);
    
    for(Lead l : trigger.new)
    {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        Boolean oldLeadIsInactive = oldLead.Trigger_Owner_Active__c == false;
        Boolean newLeadIsInactive = l.Trigger_Owner_Active__c == false;
        
        if((!oldLeadIsNo && newLeadIsNo) || (!oldLeadIsInactive && newLeadIsInactive))
        {
            if(ownerMap.containsKey(l.OwnerId) && ownerMap.get(l.OwnerId).Profile.Name == 'Sales Associate')
            {
                Lead_Cycle__c LeadCycle = new Lead_Cycle__c();
                LeadCycle.Lead__c = l.id;
                LeadCycle.Cycle_Start_Date__c = l.LastTransferDate;
                LeadCycle.Cycle_End_Date__c = system.today();
                LeadCycle.OwnerId = '00560000002VLHw';
            
                LeadCycles.add(LeadCycle);
            }
        }
    
    }   
    insert LeadCycles;
}
 
trigger EPS_OwnerActiveFalseChecker on Lead (before update) 
{
    for (Lead l : Trigger.new)
    {
        if(system.trigger.OldMap.get(l.Id).Owner_Active__c != system.trigger.NewMap.get(l.Id).Owner_Active__c)
        {
            l.Trigger_Owner_Active__c = l.Owner_Active__c;
        }
    }
}

The top trigger attempts to accomplish the following: If a User with a Profile of 'Sales Associate' has its Lead Status change to 'No' from a different value or if the field Trigger_Owner_Active__c changes to False, then create a Record associated to the Lead.

The bottom trigger attempts to copy changes in a formula field into a text field. The formula field is Owner_Active__c which looks to see if the User (Owner of the Lead) is Active, the text field is Trigger_Owner_Active__c. This serves two purposes: 1) To see if the User changes to Active = false OR if the Owner changes to a Queue (Queues cause this field to be marked false).

My issues are as follows:
1. When I change the Lead Owner to a queue, the text field changes with the formula field BUT the new Lead_Cycle__c record is not created
2. When I change the Lead Owner (User) to Active = false, the Trigger_Owner_Active__c field does NOT change with the formula field

Thanks for giving my question consideration,
Elliot
Hi All,

Relative newbie to Apex. I am looking to create a trigger that will create a Record of a custom Object I have created when a Lead Status is changed to 'No'. I would only like this Trigger to apply to Leads owned by Users with a certain Profile. Please see below:

The Profile restriction that I used doesn't seem to work and I have been spinning my tires and Google-ing around to no avail. Does anyone have any insight? Thanks.
trigger EPS_LeadCycleCreator on Lead (before update) {
    List<Lead_Cycle__c> LeadCycles = new List<Lead_Cycle__c>();
    
    for (Lead l : trigger.new) {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        if (l.Owner.ProfileId == '00e60000000rNmn' && (!oldLeadIsNo && newLeadIsNo)) {
            Lead_Cycle__c LeadCycle = new Lead_Cycle__c ();
            LeadCycle.Lead__c = l.id;
            LeadCycle.Cycle_Start_Date__c = l.LastTransferDate;
            LeadCycle.Cycle_End_Date__c = system.today();
            LeadCycle.OwnerId = '00560000002VLHw';
        
            LeadCycles.add(LeadCycle);
        }
    
    }
    
    insert LeadCycles;
}

 

Hi All,

 

I am an administrator and have not much apex experience. Having a bit of an issue with my trigger. The purpose of the trigger is to count the number of Activity Records associated to a Lead and then drop it into a field called Activity_Count__c on the Lead. The code all works as intended, but I wanted to add another parameter. I would like to be able to only have that field contain the number of Activity Records that are 'Created By' a certain User (i.e. User ID = '12345'). How would I add that contraint into the Trigger, Class and Test Class? See below.

 

Thanks,

Elliot

 

 

Class:

 

 

public with sharing class LeadActivityCount {

 

    public static Boolean didRun = false;

    public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();

 

    /*

    * Takes a set of lead IDs, queries those leads, and updates the activity count if appropriate

    */

    public static void updateLeadCounts(Set<ID> ledsIds) {

 

        if (didRun == false) { //We only want this operation to run once per transaction.

            didRun = true;

 

            //Query all the leads, including the tasks child relationships

            List<Lead> leds = [SELECT ID, activity_count__c, (SELECT ID FROM Tasks), (SELECT ID FROM Events) FROM Lead WHERE ID IN :ledsIds];

            List<Lead> updateLeds = new List<Lead>();

 

            for (Lead l : leds) {

                Integer count = l.tasks.size() + l.events.size();

 

                if (l.activity_count__c != count) {

                    l.activity_count__c = count;

                    updateLeds.add(l); //we're only doing updates to leads that have changed...no need to modify the others

                }

            }

 

            //Update the appropriate leads

            try {

                update updateLeds;

            } catch (Exception e) {

                //This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't

                //want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.

            }

        }

    }

}

 

 

Test Class:

 

 

@isTest
private class LeadsTestClassName{

public static Boolean didRun = false;
public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
   
    /*
    * Test method for this class and TaskUpdateLead and EventUpdateLead
    */
    public static testMethod void testCountTask() {
        //Setup

        Lead leds = new Lead(lastname='Test', email='1@2.com', company='Test');
        insert leds;

        //Insert our first task
        Task t = new Task(subject='Test Activity', whoId = leds.id);
        insert t;

        //Verify count
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Disconnect task from the lead
        didRun = false; //Reset
        t.whoId = null;
        update t;
        //Verify count = 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

        didRun = false; //Reset
        //Add an event
        Event e = new Event(subject='Test Event', whoId = leds.id, startDateTime = System.Now(), endDateTime = System.now());
        insert e;

        //Verify count = 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Relink the task to the lead
        didRun = false; //Reset
        t.whoId = leds.id;
        update t;

        //Verify count = 2
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(2,leds.activity_count__c);

        //Disconnect the event from the lead
        didRun = false; //Reset
        e.whoId = null;
        update e;

        //Verify count is back down to 1
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.activity_count__c);

        //Delete the task
        didRun = false; //reset
        delete t;
        //Verify count is back down to 0
        leds = [SELECT ID, activity_count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.activity_count__c);

    }
}

 

 

Trigger:

 

 

trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update) {

    Set<ID> ledsIds = new Set<ID>();
    //We only care about tasks linked to leads.
    String prefix =  LeadActivityCount.ledsPrefix;

    //Add any lead ids coming from the new data
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    //Also add any lead ids coming from the old data (deletes, moving an activity from one lead to another)
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    if (ledsIds.size() > 0)
        LeadActivityCount.updateLeadCounts(ledsIds);

}

Hi All,

Disclaimer: I am a beginner developer and am still working to understand Apex; I have strong Admin experience. Please see my code below:
 
trigger EPS_LeadCycleCreator on Lead(after update)
{
    List<Lead_Cycle__c> LeadCycles = new List<Lead_Cycle__c>();
    
    Set<Id> ownerIds = new Set<Id>();
    for(Lead l : trigger.new)
    {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        Boolean oldLeadIsInactive = oldLead.Trigger_Owner_Active__c == false;
        Boolean newLeadIsInactive = l.Trigger_Owner_Active__c == false;
        
        if((!oldLeadIsNo && newLeadIsNo) || (!oldLeadIsInactive && newLeadIsInactive))
        {
            ownerIds.add(l.OwnerId);
        }
    
    }
    
    Map<Id, User> ownerMap = new Map<Id, User>([ Select Id, ProfileId, Profile.Name From User where Id IN: ownerIDs ]);
    
    for(Lead l : trigger.new)
    {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        Boolean oldLeadIsInactive = oldLead.Trigger_Owner_Active__c == false;
        Boolean newLeadIsInactive = l.Trigger_Owner_Active__c == false;
        
        if((!oldLeadIsNo && newLeadIsNo) || (!oldLeadIsInactive && newLeadIsInactive))
        {
            if(ownerMap.containsKey(l.OwnerId) && ownerMap.get(l.OwnerId).Profile.Name == 'Sales Associate')
            {
                Lead_Cycle__c LeadCycle = new Lead_Cycle__c();
                LeadCycle.Lead__c = l.id;
                LeadCycle.Cycle_Start_Date__c = l.LastTransferDate;
                LeadCycle.Cycle_End_Date__c = system.today();
                LeadCycle.OwnerId = '00560000002VLHw';
            
                LeadCycles.add(LeadCycle);
            }
        }
    
    }   
    insert LeadCycles;
}
 
trigger EPS_OwnerActiveFalseChecker on Lead (before update) 
{
    for (Lead l : Trigger.new)
    {
        if(system.trigger.OldMap.get(l.Id).Owner_Active__c != system.trigger.NewMap.get(l.Id).Owner_Active__c)
        {
            l.Trigger_Owner_Active__c = l.Owner_Active__c;
        }
    }
}

The top trigger attempts to accomplish the following: If a User with a Profile of 'Sales Associate' has its Lead Status change to 'No' from a different value or if the field Trigger_Owner_Active__c changes to False, then create a Record associated to the Lead.

The bottom trigger attempts to copy changes in a formula field into a text field. The formula field is Owner_Active__c which looks to see if the User (Owner of the Lead) is Active, the text field is Trigger_Owner_Active__c. This serves two purposes: 1) To see if the User changes to Active = false OR if the Owner changes to a Queue (Queues cause this field to be marked false).

My issues are as follows:
1. When I change the Lead Owner to a queue, the text field changes with the formula field BUT the new Lead_Cycle__c record is not created
2. When I change the Lead Owner (User) to Active = false, the Trigger_Owner_Active__c field does NOT change with the formula field

Thanks for giving my question consideration,
Elliot
Hi All,

Relative newbie to Apex. I am looking to create a trigger that will create a Record of a custom Object I have created when a Lead Status is changed to 'No'. I would only like this Trigger to apply to Leads owned by Users with a certain Profile. Please see below:

The Profile restriction that I used doesn't seem to work and I have been spinning my tires and Google-ing around to no avail. Does anyone have any insight? Thanks.
trigger EPS_LeadCycleCreator on Lead (before update) {
    List<Lead_Cycle__c> LeadCycles = new List<Lead_Cycle__c>();
    
    for (Lead l : trigger.new) {
        Lead oldLead = trigger.oldMap.get(l.Id);
        
        Boolean oldLeadIsNo = oldLead.Status.equals('No');
        Boolean newLeadIsNo = l.Status.equals('No');
        
        if (l.Owner.ProfileId == '00e60000000rNmn' && (!oldLeadIsNo && newLeadIsNo)) {
            Lead_Cycle__c LeadCycle = new Lead_Cycle__c ();
            LeadCycle.Lead__c = l.id;
            LeadCycle.Cycle_Start_Date__c = l.LastTransferDate;
            LeadCycle.Cycle_End_Date__c = system.today();
            LeadCycle.OwnerId = '00560000002VLHw';
        
            LeadCycles.add(LeadCycle);
        }
    
    }
    
    insert LeadCycles;
}