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
Itay MaozItay Maoz 

Populating a task field from related account

I'm capturing the date a sales rep accepts a lead into their funnel using a Date_Accepted__c field on the account. I want to map this to a Date_Accepted__c field all tasks associated with the account. I've tried doing this with a formula field and a workflow and was unable to do it because Task is not a child of Account. Is there an apex trigger I could use to map this date from account to task? 
Best Answer chosen by Itay Maoz
sumit singh 37sumit singh 37
please include the Date_Accepted__c field in the query
[select Date_Accepted__c from task where   id=:accountid ];

All Answers

sumit singh 37sumit singh 37
trigger Triggertaskaccount on Account (before update) {
date date_accept;
     for(Account act:Trigger.new)
     {
         date_accept = act.Date_Accepted__c;
     }
    
    list<Task> task= [select id from Task where whatid In: Trigger.new];
    
    for(Task tsk:task)
    {
        tsk.Date_Accepted__c= date_accept;
    }
  update task;
}

 
sumit singh 37sumit singh 37
trigger Triggertask on Task (before insert) {
    
        id accountid ;
  for(Task task: Trigger.new) 
{
       Schema.SObjectType token = task.whatid.getSObjectType();

   if(token.getDescribe().getname()=='Account')
        accountid= task.whatid;
}
  if(accountid!=null)
  {
    account act= [select name from account where id=:accountid];
    
    for(Task tsk:Trigger.new)
    {
        tsk.Date_Accepted__c=act.DateAccept__c;
    }
  }

}

 
Itay MaozItay Maoz
Thanks for your help. The Account Trigger didn't work, and the task trigger gave me this errror:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger Triggertask caused an unexpected exception, contact your administrator: Triggertask: execution of BeforeInsert caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.Date_Accepted__c: Trigger.Triggertask: line 17, column 1
sumit singh 37sumit singh 37
please include the Date_Accepted__c field in the query
[select Date_Accepted__c from task where   id=:accountid ];
This was selected as the best answer
Itay MaozItay Maoz
Thank you! 
Itay MaozItay Maoz
Hi, 

Can you help me create a test for these?

Thanks,

Itay