0

I am trying to write a simple trigger that assigns the Account and Opportunity when a Task related to an Opportunity is created.

The Opportunity was easy enough to assign, but for the Account the best method seemed to be to query the accounts table where Account ID = the Opportunity's Account ID. For some reason this returns nothing. Thanks in advance for the help!

trigger TaskBeforeTrigger on Task (before insert) {
    for (Task t:Trigger.new){
        if(t.WhatID != null && ((String)t.WhatID).startsWith('006') && t.RecordTypeId == Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task').getRecordTypeId()){
            Opportunity o = new Opportunity(Id=t.WhatID);
            System.debug(o.ID);
            System.debug(o.AccountID);
            List<Account> accountList = new List<Account>();
            accountList = [SELECT ID FROM Account WHERE ID = :o.AccountID];
            System.debug(accountList[0].ID);
            t.Opportunity__c = t.WhatID;
            t.Account__c = accountList[0].ID;
        }

    }
}

1 Answer 1

0

When you have set Opportunity o = new Opportunity(Id=t.WhatID);, you've created a copy of original opportunity that knows only about its own ID and nothing else. You should quey the opportunity instead.

Also mind that queries in loop should not be used. So gather WhatId in List, query Opportunities with related Accounts once, than query needed Accounts once and run loop through Tasks again to set Account__c.

You must log in to answer this question.

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