function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sindhu NagabhushanSindhu Nagabhushan 

Update Account information on task

Hi,
 i need to write a apex trigger to achieve this - 
When a task is created related to opportunity or contact, i want to stamp the related account info in a text field. 
But i will get only related-to Id, how can i get the account information from the related-to ID

Someone please help me,

Thanks in advance
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Where do you want to persist account's info (another object perhaps) and which information would like to persist?  

Regards.
Bhanu MaheshBhanu Mahesh
Hi Sindhu,

If you want to update a field on task with account field try the following code

trigger test on task (before insert,before update) {
    Set<Id> oppIds = new Set<Id>();
    Set<Id> contctIds = new Set<Id>();
    Map<Id,Opportunity> accoutnWithOppId = new Map<Id,Opportunity>();
    Map<Id,Contact> accoutnWithContctId = new Map<Id,Contact>();
    for (Task t : Trigger.new) {
            if (t.WhatId != null && string.valueof(t.WhatId).startsWith('006') ) {
                oppIds.add(t.WhatId);
            }
            else if(t.WhoId != null && string.valueof(t.WhoId).startsWith('003')){
               contctIds.add(t.WhoId); 
            }
        }
        if(!oppIds.isEmpty()){
            for(Opportunity opp:[SELECT Id,AccountId,Account.Name,Account.Active__c FROM Opportunity WHERE Id IN : oppIds]){
                accoutnWithOppId.put(opp.Id,opp);
            }
        }
        if(!contctIds.isEmpty()){
            for(Contact con:[SELECT Id,AccountId,Account.Name,Account.Active__c FROM Contact WHERE Id IN : contctIds]){
                accoutnWithContctId.put(con.Id,con);
            }
        }
        
        for (Task t : Trigger.new) {
            if (t.WhatId != null && string.valueof(t.WhatId).startsWith('006') && accoutnWithOppId != null && accoutnWithOppId.get(t.WhatId) != null) {
                t.Account_Name__c = accoutnWithOppId.get(t.WhatId).Account.Name;    
            }
            else if(t.WhoId != null && string.valueof(t.WhoId).startsWith('003') && accoutnWithContctId != null && accoutnWithContctId.get(t.WhoId) != null){
               t.Account_Name__c = accoutnWithContctId.get(t.WhoId).Account.Name;
            }
        }

}

NOTE: Fetch the fields you want from account in the query. I have taken Account.Name as example

Regards,
Bhanu Mahesh