+ Start a Discussion
Bilal 25Bilal 25 

Salesforce Trigger needs to link task to the related object

Dear Folks,

I need your kind help to link task to related object. 

My problem here is task is created when new service tracker is created but it wont link can someone help.

Thanks in Advance
trigger PROServiceTracker on PRO_Service_Tracker__c (before insert, before update) {

    for(PRO_Service_Tracker__c PRO : trigger.new){ 
     
        List<PRO_Service_Tracker__c > PROList = 
            [SELECT id FROM PRO_Service_Tracker__c WHERE 
             (status__C = 'Booked' OR status__C = 'confirmed')   AND Assigned_PRO__c = :PRO.Assigned_PRO__c AND 
             (Start_Date_Time__c = :PRO.Start_Date_Time__c) AND id != :PRO.id];
        
        if(PROList.size() >0 && PRO.status__C != 'cancelled'){
            
            PRO.addError('PRO is already booked on your requested time. ');
     
     
   Id PRORecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosById().get('0124L0000008TaH').getRecordTypeId();
   
   System.debug('PRORecordTypeId'+ PRORecordTypeId); 
    
    List<Task> lTask = new List<Task>();

      if(Trigger.isBefore && trigger.isInsert) {
           for(PRO_Service_Tracker__c PS: Trigger.new) {

               if(PS.Status__c == 'Booked' ){
                // if(lead_rt.get(PS.RecordTypeID).getName() != 'PRO_Service_Task') continue;
                 task t = new Task( 
                 whatID = PS.Id,
                 //whoID = PS.Id,
                 recordtypeId = PRORecordTypeId,
                 Subject = 'PRO Task',
                 Priority = 'High',
                 Status = 'Not Started',
                 ActivityDate = PS.Start_Date__c,
                 Start_Time__c = PS.Start_Time__c,
                 ownerID = PS.Assigned_PRO__c
                 );
                 lTask.add(t);   
               }
            }
          system.debug('Before insert Task'+ lTask);
        insert lTask;
          system.debug('After insert Task'+ lTask);
      }
    
}
           }
      
    }