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;
}
}
}