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
Matthew KeefeMatthew Keefe 

Setting AccountId on Task

When inserting a new Task, AccountId cannot be set because it's set by the system. Is there a way to make sure the system sets it? I've tried setting the WhatId and the WhoId, but the AccountId is still not set after inserting the Task.

Here's some sample code:

System.Savepoint sp = Database.setSavePoint();

User TestOwner = [Select Id from User where Id = :UserInfo.getUserId()];

Account TestAccount = new Account(Name = 'Test Account');
insert TestAccount;

Contact TestContact = new Contact(FirstName='TEST First Name'
    ,LastName='TEST Last Name'
);

TestContact.AccountId = TestAccount.Id;
insert TestContact;

Task NewTask = new Task(Subject='Test Task'
    ,Status='Completed'
    ,ActivityDate=Date.today().addDays(-7)
    ,OwnerId=TestOwner.Id
    ,WhatId=TestAccount.Id
    ,WhoId=TestContact.Id
    //,AccountId=TestAccount.Id
);

insert NewTask;

system.debug('New Task: ' + NewTask);
system.debug('New Task AccountId: ' + NewTask.AccountId);

Database.rollback(sp);

Thanks!
Matt
Best Answer chosen by Admin (Salesforce Developers) 
Matthew KeefeMatthew Keefe
Figured it out.. simple mistake, hate it when that happens..

Turns out Salesforce was indeed setting the AccountId, I just didn't have it because Task needs to be queried to get it from the database first.

        ...
        insert NewTask;
        
        NewTask = [select id, subject, status, activitydate, 
            ownerid, whatid, whoid, accountid 
            from task 
            where id=:NewTask.id];
        
        system.debug('New Task: ' + NewTask);
        system.debug('New Task AccountId: ' + NewTask.AccountId);
        ...