function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Alex DornAlex Dorn 

Lead Apex Trigger last activity subject

This is the first time I have used an Apex trigger and I am struggling to get it to work. I took the code used from here https://developer.salesforce.com/forums?id=906F00000008yXUIAY. And then adjusted it so it fit for leads and the names of fields I currently have in my for my leads. I am not getting any errors now, but the code does not seem to be doing anything and is active. The items I changed were changing any opportunity or opp to lead, whatid to id to get rid of errors, and the name of fields. What i want to have happen is the subject of activities to become its own field, and only display the last activity subject. The Last_Activity_Date_c field is a field I created that uses a simple formula that pulls the last activity date through. If anyone has any insight it would be greatly appreciated. Here is my code for reference:

trigger NextTastInfo on Lead (after insert, after update) {
          

  if(Trigger.new.size() == 1 ) {

    Lead tk = Trigger.New[0];
    String str = tk.id;
    if(str != null && str.substring(0,3)== '006')
    {

         Lead lead = [select OwnerId,Last_Activity_Subject__c,Last_Activity_Date__c from Lead where Id = :tk.id ];

        List<Task> tskMin = [Select ActivityDate,Subject From Task where id=:tk.id and  what.type = 'Lead' and isClosed = false order By ActivityDate limit 1];

        if (tskMin.size()>0) {
                lead.Next_Step_Date__c=tskMin[0].ActivityDate;
                lead.Last_Activity_Subject__c=tskMin[0].Subject;
        }
        else {
                lead.Next_Step_Date__c=null;      
                lead.Last_Activity_Subject__c='';
        }
        update lead;
    }
}
}
Best Answer chosen by Alex Dorn
Vinit_KumarVinit_Kumar
Alex,

You don't need a Trigger on Lead rather the Trigger should be on Task whenever a new Task is inserted ,the Trigger would copy the Subject of the Task and update the Last_Activity_Subject_C of related Lead.So,you should be looking at something like below :-
trigger updateRelatedLead on Task (after insert,after update) {

 List<Id> LeadIds = new List<Id>();
 List<Lead> LeadList = new List<Lead>();

for(Task t :trigger.new)
    {
	if(t.whoId!=null)
	{
        Schema.SObjectType tType= t.whoId.getSObjectType();
        if(tType == Lead.Schema.SObjectType)
        {
            LeadIds.add(t.WhoId);
        }
    }
	}
	//Querying the related Lead based on whoId on Task
	Map<Id,Lead> LeadMap =  new Map<Id,Lead>([select id,Last_Activity_Subject_C from Lead where id in:LeadIds]);
	
	for(Task t :Triger.new)

		for(Lead l : LeadMap.Values())
		{
			l.Last_Activity_Subject_C = t.subject;
			LeadList.add(l);
		}
	}
	// updating the Lead
	if(LeadList.size()>0)
	{
		update LeadList;
	}
}
If this helps,please mark it as best answer to help others :)

All Answers

Ramesh KallooriRamesh Kalloori
the above trigger is recursive.

Please go through below code.

public class LocationControl{
public static boolean inFutureContext = false;
}
trigger NextTastInfo on Lead (after insert, after update) {
          
if(!LocationControl.inFutureContext)
{
  if(Trigger.new.size() == 1 ) {

    Lead tk = Trigger.New[0];
    String str = tk.id;
    if(str != null && str.substring(0,3)== '006')
    {

         Lead lead = [select OwnerId,Last_Activity_Subject__c,Last_Activity_Date__c from Lead where Id = :tk.id ];

        List<Task> tskMin = [Select ActivityDate,Subject From Task where id=:tk.id and  what.type = 'Lead' and isClosed = false order By ActivityDate limit 1];

        if (tskMin.size()>0) {
                lead.Next_Step_Date__c=tskMin[0].ActivityDate;
                lead.Last_Activity_Subject__c=tskMin[0].Subject;
        }
        else {
                lead.Next_Step_Date__c=null;      
                lead.Last_Activity_Subject__c='';
        }
LocationControl.inFutureContext=true;//to avoid recursive.
        update lead;
    }
}
}
}


thanks,
Ramesh
Alex DornAlex Dorn
I used your class and code Ramesh, but when i log activities the subject does not display in the field like I wanted. I'm lost at this point do you have any more advice?
Ramesh KallooriRamesh Kalloori
can you please elaborate the request.

thanks,
Ramesh
Alex DornAlex Dorn
What I want to have happen is anytime someone logs an activity the activity subject of the latest one to fill the field Last_Activity_Subject_C. The Last_activity_date_c field is automatically updated with the last activity date. I do not need the next_step_date_c field its just what the person i copied from used. So the code I have could be way off from what I actually need.
Vinit_KumarVinit_Kumar
Alex,

You don't need a Trigger on Lead rather the Trigger should be on Task whenever a new Task is inserted ,the Trigger would copy the Subject of the Task and update the Last_Activity_Subject_C of related Lead.So,you should be looking at something like below :-
trigger updateRelatedLead on Task (after insert,after update) {

 List<Id> LeadIds = new List<Id>();
 List<Lead> LeadList = new List<Lead>();

for(Task t :trigger.new)
    {
	if(t.whoId!=null)
	{
        Schema.SObjectType tType= t.whoId.getSObjectType();
        if(tType == Lead.Schema.SObjectType)
        {
            LeadIds.add(t.WhoId);
        }
    }
	}
	//Querying the related Lead based on whoId on Task
	Map<Id,Lead> LeadMap =  new Map<Id,Lead>([select id,Last_Activity_Subject_C from Lead where id in:LeadIds]);
	
	for(Task t :Triger.new)

		for(Lead l : LeadMap.Values())
		{
			l.Last_Activity_Subject_C = t.subject;
			LeadList.add(l);
		}
	}
	// updating the Lead
	if(LeadList.size()>0)
	{
		update LeadList;
	}
}
If this helps,please mark it as best answer to help others :)
This was selected as the best answer
Alex DornAlex Dorn
Vinit that worked just had to add a g to trigger in line 20, and a { between lines 16 and 17. If I wanted this to work for opportunities as well could I just clone the code and change lead to opportunity for every instance lead is in the code?
Vinit_KumarVinit_Kumar
Yes Alex,that should do the trick :)
Alex DornAlex Dorn
I copied the code and just replaced every Lead with Opportunity there are no errors, but the code doesn't work like the lead code, the subject is not put in. Do you have any idea of what else I may have to change? Here is the code:
trigger updateRelatedOpportunity on Task (after insert,after update) {

List<Id> OpportunityIds = new List<Id>();
List<Opportunity> OpportunityList = new List<Opportunity>();

for(Task t :trigger.new)
    {
    if(t.whoId!=null)
    {
        Schema.SObjectType tType= t.whoId.getSObjectType();
        if(tType == Opportunity.Schema.SObjectType)
        {
            OpportunityIds.add(t.WhoId);
        }
    }
    }
    {
    //Querying the related Opportunity based on whoId on Task
    Map<Id,Opportunity> OpportunityMap =  new Map<Id,Opportunity>([select id,Last_Activity_Subject__C from Opportunity where id in:OpportunityIds]);
    
    for(Task t :Trigger.new)

        for(Opportunity l : OpportunityMap.Values())
        {
            l.Last_Activity_Subject__C = t.subject;
            OpportunityList.add(l);
        }
    }
    // updating the Opportunity
    if(OpportunityList.size()>0)
    {
        update OpportunityList;
    }
}
Vinit_KumarVinit_Kumar
Alex,

whoId needs to be replaced with whatId .
Alex DornAlex Dorn
Vinit is there anything I have to change to get it to deploy correctly i get these errors: 
updateRelatedLead               Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
updateRelatedOpportunity    Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
Deploy Error                             Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is required.
Vinit_KumarVinit_Kumar
You need to create the Test class for your Trigger,then only you will be able to deploy the same !!
Alex DornAlex Dorn
I created a new question for it if you can give me help writing the test.
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AYGqIAO#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Apex_Code_Development&criteria=OPENQUESTIONS&id=906F0000000AYeUIAW
uma52551.3972270309784705E12uma52551.3972270309784705E12
Hi Vinit kumar,

I am trying to write similar trigger can you please help me in coding this trigger. 

In the Opportunity Object I have created a field called Next Activity. This Field should display the Subject of the next scheduled activity... I am literally confused. I have to Write trigger on Opportunity or On Task and Event? If I have to write on Opportunity can you please help me in writing the code. Thanks In advance!