function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
hamad_amaralhamad_amaral 

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.

Best Answer chosen by Admin (Salesforce Developers) 
IvarIvar

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

ThomasTTThomasTT

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

Message Edited by ThomasTT on 10-22-2009 02:19 AM
IvarIvar

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');

 

 

This was selected as the best answer
hamad_amaralhamad_amaral
Thank you guys