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
Virgilio GanataVirgilio Ganata 

Update Parent (Contact) record based on Task created

Hi,

I am trying to update parent record (Contacts) based on Task

Here is my trigger
 
trigger updateContactFromTask on Task (before insert, before update)
{

Map<Id,Contact> contactMap = new Map<Id,Contact>();
Set<id> Ids = new Set<id>();
for (Task tk: Trigger.new) {
Ids.add(tk.WhoId);
}

Map<id,Contact> contactMap2 = new Map<id,Contact>([Select Id, Title from Contact Where Id in :Ids]);

for (Task t: Trigger.new)
if(t.CreatedDate!=system.today()&&Contact.LeadSource != NULL)
{
Contact l = contactMap2.get(t.WhoId);
l.LeadSource = 'Test1234';
contactMap.put(l.id,l);
}
update contactMap.values();

}

So my criteria: 
if(t.CreatedDate!=system.today()&&Contact.LeadSource != NULL)
If Task is created Today and Contact LeadSource Not Equal to NULL, This works and sets a Leadsource value, However when I set the LeadSource to another value Say Web. Trigger still fires for update even it has a value. Perhaps something wrong with my trigger.

Thank you in advanced
 
Shashikant SharmaShashikant Sharma
Hi,

You could use Trigger.isInsert to identify that Task is created not update.
 
trigger updateContactFromTask on Task (before insert, before update)
{

Map<Id,Contact> contactMap = new Map<Id,Contact>();
Set<id> Ids = new Set<id>();
for (Task tk: Trigger.new) {
Ids.add(tk.WhoId);
}

Map<id,Contact> contactMap2 = new Map<id,Contact>([Select Id, Title from Contact Where Id in :Ids]);

for (Task t: Trigger.new)
if( Trigger.isInsert ) {
   if(t.CreatedDate!=system.today()&&Contact.LeadSource != NULL)
   {
     Contact l = contactMap2.get(t.WhoId);
     l.LeadSource = 'Test1234';
     contactMap.put(l.id,l);
    }
}
// similarly yo could do on  update
if( Trigger.isUpdate ) {

// actions on task udpate

}

update contactMap.values();

}



Thanks
Shashikant
Ravi Dutt SharmaRavi Dutt Sharma
Hi Virgilio,

Are you sure that the Contact you are accessing on line 13 is the the Contact associated with WhoId of task? Can you try putting a system.debug to check which Contact record it is referring to?
Virgilio GanataVirgilio Ganata

@Ravi, 

Yes, I am sure that the contact is associated with the WhoID creating the task from the Contact record itself.