+ Start a Discussion
t4runjaint4runjain 

How to create Account and Task in single DML Statement

Hello,

I am trying to create Parent & Child records in single DML statement, I am able to do the same for most of the object, but I have a requirement to create Account and Task in single DML.

I am getting "Field is not writeable: Task.What" error message. Here is the code I am trying to do so:


Account accReference = new Account(
     Autodesk_CSN__c ='1322'//external id
);

Account acc = new Account(Name='test', Autodesk_CSN__c='1322');

Task task = new Task();
task.What = accReference, // here is the problem, not sure what would be the relationship field name to refer parent?
task.ActivityDate=Date.Today(),
task.Subject = 'Testing',
task.Priority = 'High',
task.OwnerId = UserInfo.getUserId();

Database.SaveResult[] results = Database.insert(new SObject[] { acc, task });

Any help would be appreciated.

Thanks,
Tarun
v varaprasadv varaprasad
Hi Tharun,

Use 

task.WhatId = accReference;

Task task = new Task();
task.WhatId = accReference; 
task.ActivityDate=Date.Today();
task.Subject = 'Testing';
task.Priority = 'High';
task.OwnerId = UserInfo.getUserId();

Sample code : 
 
Account acc=new Account(Name='Blog Acc 8', Master_Id__c='Blog Acc 8');
Contact cont=new Contact(FirstName='Bob', LastName='Buzzard', Account=new Account(Master_Id__c='Blog Acc 8'));
 
insert new List<Sobject>{acc, cont};



Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com

 
t4runjaint4runjain
Hi @Varaprasad,

Tried that giving following error:
Illegal assignment from Account to Id

Thanks,
Tarun 
v varaprasadv varaprasad
Task.WhatId =accReference.id;