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
learn1.3947400898749973E12learn1.3947400898749973E12 

Update A Contact Check Box when a Task is created with a specific picklist value

I can't understand why the trigger below is not working. All I am wanting to do is update a Contact checkbox when a Task is created with a custom picklist field has a specific value:

trigger UsefulActivity on Task (after insert, after update)
{
for(Task t : trigger.new)
{
  for(Contact c : [select Id, Had_Useful_Activity__c from Contact where Id=:t.WhatID])
  {
   if(t.Result__c == 'Meeting')
   {
    c.Had_Useful_Activity__c = true;
   }
  }
}
}
Rob MorrisRob Morris
2 minor things: should be whoID instead of WhatID and you are missing an update c; command to save the changes. see updated workign code below:

trigger UsefulActivity on Task (after insert, after update)
{
for(Task t : trigger.new)
{
  for(Contact c : [select Id, Had_Useful_Activity__c from Contact where Id = :t.WhoID])
  {
   if(t.Result__c == 'Meeting')
   {
    c.Had_Useful_Activity__c = true;
    update c;
   }
  }
}
}
Ajay_SFDCAjay_SFDC
Hi there ,

You should not use the query inside the for loop . It may hit the governor limit . Use Set,Map Collections .

trigger UsefulActivity on Task (after insert, after update)
{
set<Id > setContact = new set<Id>();
for(Task t : trigger.new)
{
  if(t.Result == 'Meeting')
  {
   setContact.add(t.WhoID);
   }
}

List<Contact> lstContactToInsert = new List<Contact>();

for(Contact c : [select Id, Had_Useful_Activity__c from Contact where Id IN :setContact])
{
  c.Had_Useful_Activity__c = true;
   lstContactToInsert.add(c);
}

if(lstContactToInsert.size() > 0)
update lstContactToInsert;

}

Thanks ,
  Ajay
Carolina Ruiz MedinaCarolina Ruiz Medina
Hi,
Totally agree with @Ajay_SFDC , try to bulkify your triggers and your code to don't hit limits, appart from that you got great answers. 
I attach here a link about Apex Patterns that might be help you too : https://github.com/financialforcedev/fflib-apex-common
:)