You need to sign in to do that
Don't have an account?

Field expression not allowed for generic SObject
Hi guys,
When I use the following piece of code I get the error "Field expression not allowed for generic SObject". Can you tell me why even after cast the generic sObject to the correct class I get the error? Is there any solution to get properties from a generic sObject after cast it to a specific sObject type (example an Account or Lead)?
public static void setCode(sObject[] objs){
for (sObject o:objs)
{
if (o.getSObjectType() == Account.sObjectType)
{
o = (Account) o;
}
else if (o.getSObjectType() == Lead.sObjectType)
{
o = (Lead) o;
}
tempCode = generateNewCode(o.Name);
...
Thanks in advance.
You cannot use direct reference or assignment when working with sObjects. Instead you must use their get and put methods.
So instead of
String strObjectName = mySObject.Name;
you need to do:
String.strObjectName = String.valueOf( mySObject.get('Name') );
Same applies to assigning values to sObjects. Instead of:
mySObject.Name = 'MyName';
you need to do:
mySObject.put('Name', 'MyName');
All Answers
Hmm... is it because you defined o as SObject? like "sObject o"?
Good news! Even though o is SObject type, you can do o.get('Name')! (cast it to String)
ThomasTT
You cannot use direct reference or assignment when working with sObjects. Instead you must use their get and put methods.
So instead of
String strObjectName = mySObject.Name;
you need to do:
String.strObjectName = String.valueOf( mySObject.get('Name') );
Same applies to assigning values to sObjects. Instead of:
mySObject.Name = 'MyName';
you need to do:
mySObject.put('Name', 'MyName');