I want to update existing task records but a new record gets created instead . What am I doing wrong.


public static void Activities(List<Account> accounts) {
  Set<Id> persAccIds = (new Map<Id, Account> (accounts)).keySet();

  set<id> TaskWhatIDs = new set<id> ();
  for (Task t :[Select WhatId from Task where Subject = 'Sending' and Status != 'Completed' and whatId IN :persAccIds]) {
      System.debug('persAccIds: ' + persAccIds);
              System.debug('soql: ' + [select id, PersonEmail, FirstName, LastName, SsoId__c, PersonContactId FROM Account WHERE id IN :persAccIds]);

  List<Task> taskList = [Select id FROM Task where id IN :TaskWhatIDs];
  for (Account acc : [select id, PersonEmail, FirstName, LastName, SsoId__c, PersonContactId FROM Account WHERE id IN :persAccIds]) {
    //if (TaskWhatIDs.contains(acc.Id))
           System.debug('acc: ' + acc);

    Profile Obj = new Profile(acc);
    Task gTask = new Task();
    gTask.Status = 'Not Started';
    gTask.Description = System.JSON.serialize(Obj);
    gTask.WhoId = acc.PersonContactId;
    gTask.WhatId = acc.Id;
    gTask.Subject = 'Send';

  if (taskList.size() > 0) {
      System.debug('taskList: ' + taskList);
    upsert taskList;
  • 1
    You're not binding an ID with the new instance of Task which you're creating in for loop. Something like this: gTask.id = task.id; Jan 23 '20 at 7:45
  • Are you trying to update accounts's tasklist? Jan 23 '20 at 7:52
  • @rahulgawale That is what I want to achieve indeed.
    – Thomas
    Jan 23 '20 at 7:57

You don't need to have two queries on Task object, rather you can get them in a single query on account object.

Account[] accounts = [SELECT id, (SELECT WhatId FROM Tasks where Subject = 'Sending' and Status != 'Completed') FROM Account WHERE Id IN :accounts];
Task[] taskList = new List<Task>();
for (Account acc : accounts){
    for(Task taskObj: acc.Tasks){
        /// Update the fields here
update taskList;

I suggest this sort of code if there is only ever one Task at most per Account:

Map<Id, Task> whatIdToTasks = Map<Id, Task>();
for (Task t : [...]) {
    whatIdToTasks.put(t.whatId, t);

for (Account acc : [...]) {
    // Update existing Task or create new one
    Task gTask = whatIdToTasks.get(acc.Id);
    if (gTask == null) gTask = new Task(Id = acc.Id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.