+ Start a Discussion
ChuckchoChuckcho 

How to get Account Name instead of ID using a trigger

I have the following trigger on tasks to update Account custom field from Agreements custom Object. Account is a custom lookup field on Agreements. The triggers works but updates with the Account ID. I'm trying to update with the Account Name. Can someone please advise how to get the name instead of ID. Thanks for the help

 

trigger updateAccounttname on Task (before insert, before update) {

Set<Id> AccnameIds = new Set<Id>();
for(Task t : trigger.new){
String wId = t.WhatId;
if(wId!=null && wId.startsWith('a1J') && !AccnameIds.contains(t.WhatId)){
AccnameIds.add(t.WhatId);
}
}
 List<Agreement__c> taskAccountname = [Select Id, Account__C from Agreement__C where Id in :AccnameIds];
Map<Id, Agreement__C> AccountnameMap = new Map<Id, Agreement__C>();
for(Agreement__c B : taskAccountname){
AccountNameMap.put(B.Id,B);
}
// Update custom task field with custom Agreement field
for(Task t : trigger.new){
String wId = t.WhatId;
if(wId!=null && wId.startswith('a1J')){
Agreement__C thisAcc = AccountNameMap.get(t.WhatId);
if(thisAcc!=null){t.Account__C = thisAcc.Account__C;}
}
}
}

kiranmutturukiranmutturu

with in the trigger u can't get the reference fields ..so once you got the ids u need to query the respective object for further fields what ever u want..

vishal@forcevishal@force

Hi,

 

By Account Name, do you mean you will be querying your Agreement records on the basis of the Account Name?

Assuming this is the case, below is the trigger. Let me know if this does not help.

 

trigger updateAccounttname on Task (before insert, before update) 
{
	Set<Id> setAccountIds = new Set<Id>(); // set to store all the Account Id's
	Set<String> AccnameIds = new Set<String>(); // set to store all the Account Names
	
	for(Task t : trigger.new)
	{
		String wId = t.WhatId;
		
		if(wId!=null && wId.startsWith('a1J') && !AccnameIds.contains(t.WhatId))
		{
			setAccountIds.add(t.WhatId); // add all the Account Id's
		}
	}

	for(Account acc : [Select Name From Account Where Id IN :setAccountIds])
	{
		AccnameIds.add(acc.Name); // Add all the Account Names
	}
	
	List<Agreement__c> taskAccountname = [Select Id, Account__c from Agreement__C where Account__r.Name in :AccnameIds];
	Map<Id, Agreement__C> AccountnameMap = new Map<Id, Agreement__C>();
	
	for(Agreement__c B : taskAccountname)
	{
		AccountNameMap.put(B.Id,B);
	}
	
	// Update custom task field with custom Agreement field
	
	for(Task t : trigger.new)
	{
		String wId = t.WhatId;
		
		if(wId!=null && wId.startswith('a1J'))
		{
			Agreement__C thisAcc = AccountNameMap.get(t.WhatId);
			if(thisAcc!=null)
			{
				t.Account__C = thisAcc.Account__C;
			}
		}
	}
}