1

I'm trying to get value of a lookup field, by using SObject.Get().

I'm using this method because i want to make this class generic.

That's the relevant piece of code:

for(SObject sobject_i : Trigger.new) {
    String test = (String)sobject_i.get('AccountId'); 
}

I'm able to fetch that value, but i want to be able to fetch Account.Name.

is it possible without using queries?

3

You won't be able to get the values of the related fields. You will be able to access only those fields which are present on the object on which trigger got fired. And as you are trying to access the related fields, they won't be present in the object your trigger is fired on. You'll need create the Set<Id> with the Ids and will have to query to get them. Related object's fields won't be available in Trigger.New context variable.

Excerpt from this blog

Every time you run the Trigger, the Account is null even though there is a valid Id in AccountId. The reason is that for scalability, the Force.com platform doesn't perform an in-memory lookup for each relationship in your object. You need to do that yourself. The good thing is that the solution is relatively painless and is safe for bulk transactions.

You can get all the fields of the same object on which trigger is fired using your above code

for(SObject sobject_i : Trigger.new) {
    String test = (String)sobject_i.get('AccountId'); 
}

For getting the related fields, you will have to do a explicit query, store it in map and then you can use that map to get the required fields.

Set<Id> setAccountIds = new Set<Id>();
for(SObject sobject_i : Trigger.new) {
    setAccountIds.put((Id)sobject_i.get('AccountId')); 
}

Map<Id, Account> mapAccounts = new Map<Id, Account>([SELECT Id, Name from Account where Id IN : setAccountIds]);
  • So no matter what lookup i try to use, even a custom one, let's say "User__c", i can't get the value "User__r.Name" using get() ? – Dana Griff Mar 27 at 9:21
  • 1
    Yup, you will get only the values of the fields which are present on that particular object i.e. In your example, you will get User__c i.e UserId but not User__r.Name – Vijay Ganji Mar 27 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.