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
Jim MontgomeryJim Montgomery 

adding account id to task on custom object

I have a custom object names Project. When I log a call as a task, the related to is the project Id. I assume that is the WhatId field on the task object. I need to be able to also have this task show up on the accounts activity history related list as well. I have a trigger, but get the error "Field is no writeable Task.AccountId."
Prem RPrem R
Hi Jim,  

Can you please paste your code here to check the issue.  

Thanks,
Prem
Jim MontgomeryJim Montgomery
trigger FFTaskAccountId on Task (after insert, before update) {
if(trigger.isUpdate && trigger.isBefore){
For (Task T : trigger.new){

            if(T.Task_AccountId__c != NULL || T.Task_AccountId__c != '')
            {
                
           T.AccountId = T.Task_AccountId__c;     
        }
}
}


if(Trigger.isInsert && trigger.isafter){
Task T = [select Id,WhatID,AccountID from task where Id=:trigger.new[0].Id];
if(T.Task_AccountId__c != NULL || T.Task_AccountId__c != '')
            {
                
           T.AccountId = T.Task_AccountId__c; 
                update t:
        }
 
}
}
Prem RPrem R
I noticed you have created custom account lookup field and while creating task record you are assigning account id value from custom account lookup field. correct? 
Jim MontgomeryJim Montgomery
Correct. Jim Montgomery Manager, Sales Intelligence Operations North America Tax & Accounting 20101 Hamilton Ave. Torrance, CA 90502 877-346-7148 jim.montgomery@wolterskluwer.com
Prem RPrem R
Hi, 

As per salesforce you can't use AccountId field in apex code. When you are updating whatId as account then this particular field will update automatically in backend.  We can use only WhatId and WhoId to relate with task object. 

If you want to integrate with more than one object you can go for custom lookup field which you have already created.  

Thanks,
Prem
Prem RPrem R
Please see below for more details which I got from SFDC document
Field
Account Id
Type
reference
Properties
Group, Sort, Filter, Nillable
Description
Represents the ID of the related Account. The AccountId is determined as follows.
If the value of WhatId is any of the following objects, then Salesforce uses that object’s AccountId.
Account
Opportunity
Contract
Custom object that is a child of Account

If the value of the WhatId field is any other object, and the value of the WhoId field is a Contact object, then Salesforce uses that contact’s AccountId. (If your organization uses Shared Activities, then Salesforce uses the AccountId of the primary contact.)
Otherwise, Salesforce sets the value of the AccountId field to null.