You need to sign in to do that
Don't have an account?
softcloud2009
using trigger.new
To prevent the soql query limit on triggers, i would like to replace this line of code:
for (Order_Detail__c orderDetail :trigger.new)
{
Id acctID = orderDetail.Account__c;
Account account = [select Id, parentId from Account where Id = :acctID limit 1];
Id parentAccountId = account.parentId;
}
with this one:
for (Order_Detail__c orderDetail :trigger.new)
{
Id parentAccountId = Trigger.newMap.get(orderDetail.Id).Account__r.ParentId;
}
However, I got an error attempt to de-reference a null object.
I apex you can not get the value of related data without quering the related data.
In the following ex. Account__r is null object.
Id parentAccountId = Trigger.newMap.get(orderDetail.Id).Account__r.ParentId;
Better way to do yoor code is:
Set <ID> setOrderId = new set<ID>();
for (Order_Detail__c orderDetail :trigger.new)
{
setOrderId.add(orderDetail.Account__c);
}
Account [] accounts = [select Id, parentId from Account where Id in :setOrderId];
for(Account a: accounts ){
Id parentAccountId = a.parentId;
}
You need to put into orderDetail.Account__c into a Set as demonstrated, but then put the results of the Select statement into a map : Map<ID, Account> m = new Map<ID, Account>([select id, parentid from Account where id in :accids]);
Then you loop through the trigger again and use the value in orderDetail.Account__c field to look up the key field in the map to return the parent Id using the get method for the map.