[SalesForce] Apex Trigger to Create Task from Lead

I need some assistance.

Aim : create a Trigger that creates a task from a lead record when certain criteria is met.

Lead criteria :

Object : lead
RT: Registration
lead Source : Property

Task criteria ;

Status : not started
Priority : normal
Subject : should be populated with lead source picklist value
Type: action
Owner : lead owner

This is my logic ( see below) however every-time I create a lead with the criteria listed above I am not getting a task being generated

Really looking forward to your help

trigger CreateTaskOnLead on Lead (after insert) {
    List<Task> lTask = new List<Task>();
      Task t;
      if(Trigger.isAfter) {
        if(Trigger.isInsert) {
           for(Lead l: Trigger.new) {

               if((l.LeadSource != null)&&(l.LeadSource == 'Property')){
                 t = new Task(); 
                 t.OwnerId = l.OwnerId;
                 t.Subject = 'Property';
                 t.Priority = 'Normal';
                 t.Status = 'Not Started';
                 t.Type = 'Action';
                 lTask.add(t);   
               }
            }
            if(!lTask.IsEmpty())
                insert t;
           }        
      }
}

Best Answer

I do not see where you are checking for record type is your trigger so going to add that in the answer. As per others commented you need to set the whatID for the Owner.

Another issue you need to account for is assignment rules. If the owner changes then you may want to reassign the tasks to the new lead owner. You would query for the tasks related to the leads where the owner is changing and update the task owner appropriatly

trigger CreateTaskOnLead on Lead (after insert) {
    Map<ID,schema.RecordTypeInfo> lead_RT = lead.sObjectType.getDescribe().getRecordTypeInfosByID();

    List<Task> lTask = new List<Task>();

      if(Trigger.isAfter && trigger.isInsert) {
           for(Lead l: Trigger.new) {

               if(l.LeadSource == 'Property'){
                 if(lead_rt.get(l.RecordTypeID).getName() != 'Registration') continue;
                 task t = new Task( 
                 whatID = l.id,
                 Subject = 'Property',
                 Priority = 'Normal',
                 Status = 'Not Started',
                 Type = 'Action',
                 ownerID - l.ownerID
                 );
                 lTask.add(t);   
               }
            }
        insert t;
      }
}
Related Topic