7

Let's say I have an sObject queried and want to dynamically get a specific field value.

I need it to be dynamic so that it can be a different field through an input.

sObject obj = [SELECT Id, Name, ParentId FROM Account WHERE Id = 'someId'];
Id selectedId = obj.get('ParentId');

I get this error:

Error: Compile Error: Illegal assignment from Object to Id
Nathan Williams
  • 3,445
  • 1
  • 29
  • 49

3 Answers3

11

When working with sObjects, if you want to reference a field variable you must reference the data type. To explicitly cast a data type for a variable, simply add the data type in parentheses before you get the variable from the sObject.

For example:

Account a = new Account(Name='Test');
sObject sA = a;
string sA_name = (string)sA.get('Name');

Another example:

// Suppose the Account object has a custom DECIMAL field called myDecimal__c

Account a = new Account(Name='Test',myDecimal__c=3.1415926535897);
sObject sA = a;
decimal theDecimal = (decimal)sA.get('myDecimal__c');

Essentially, for sObjects, the compiler doesn't know what the data type is if you try to reference a field value, so you have to explicitly tell the compiler what the data type of the field is. This may seem odd, but in fact, it's the key to the generality of sObjects.

Note: casting data types come in to play a lot when dealing with data coming from other electronic sources. You might even find a reason someday where you will need to cast something as (list<myFavoriteClass>).

Scott Pelak
  • 7,514
  • 2
  • 39
  • 72
5
sObject obj = [SELECT Id, Name, ParentId FROM Account WHERE Id = 'someId'];
Id selectedId = Id.valueOf(String.valueof(obj.get('ParentId')));

Just expanding on Daniel answer the ID.valueof() expects string as parameter.

There is definaltely other way to do this

Id selectedId = [SELECT Id, Name, ParentId FROM Account WHERE Id = 'someId'].ParentId;

The problem with second method is we cannot go dynamic everytime .

Mohith Shrivastava
  • 91,131
  • 18
  • 158
  • 209
3

When you use the get method of an sObject, it always returns back an Object. You need to use Id.valueOf to get it to be an Id:

sObject obj = [SELECT Id, Name, ParentId FROM Account WHERE Id = 'someId'];
Id selectedId = Id.valueOf(obj.get('ParentId'));
Daniel Hoechst
  • 25,020
  • 7
  • 79
  • 114