I'm trying to create a trigger on the Task object that would stamp a field from a related object (Account), the field is Account Type.

I'm unable to use flow for this requirement since there are several tasks coming from third party apps and they cause flow errors.

I created the following Apex trigger on the Task, but instead of stamping the Account.Type into the tasks, this is just deleting the Account Type.

Would someone be able to point out the error so I can understand and fix it. Thanks

trigger AccountTypeStamp on Task (after insert) {

  List<Account> acclistupdate = new List<account>();
 Map<Id,string> mapaccounttype = new Map<Id,string>();

  for (Task t : trigger.New) {
    if (t.WhatId != Null && t.WhatId.getSobjectType() == Account.getSObjectType()) {
      mapaccounttype.put(t.WhatId,t.Account_Type_Update__c );
  for(account acc: [SELECT Id,Type FROM account where id=:mapaccounttype.keyset() AND Type!= Null]){
  acc.Type = mapaccounttype.get(acc.id);

  update acclistupdate;

1 Answer 1


If the aim is to set a value from the Account on the Task, something like this should work (untested by me).

trigger AccountTypeStamp on Task (before insert) {

    Set<Id> accountIds = new Set<Id>();
    for (Task t : Trigger.new) {
        if (t.WhatId != null && t.WhatId.getSObjectType() == Account.SObjectType) {

    // Avoid the query when the WhatId is not the type we are interested in
    if (accountIds.size() > 0) {
        Map<Id, Account> accounts = new Map<Id, Account>([
            select Id, Type from Account where Id in :accountIds
        for (Task t : Trigger.new) {
            Account a = accounts.get(t.WhatId);
            if (a != null) {
                // Before insert trigger so this change will be saved
                t.Account_Type_Update__c = a.Type;
  • That makes sense, I just tested it and it works great! thanks for the prompt response!
    – Marco
    Jul 17, 2022 at 11:09
  • Hi @Marco, Glad it helped.
    – Keith C
    Jul 17, 2022 at 11:46
  • Hi @Keith I noticed that is not working for tasks synced from another software, is there anything I can change or should I look into creating an asynchronous trigger. thanks
    – Marco
    Jul 18, 2022 at 9:54
  • @Marco The trigger will always run; is the other software doing updates not inserts?
    – Keith C
    Jul 18, 2022 at 10:29
  • 1
    Hello @keith I found the issue and it's because the software API integration is leaving the whatid field empty. I update the trigger to set the value from the contact. Hopefully it will work
    – Marco
    Jul 18, 2022 at 21:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .