+ Start a Discussion
sathya_sam3sathya_sam3 

Access sobject field which is defined dynamically

Hi I have a custom setting(CS) field where am saving a SOQL Query. I am passing this query thru the CS field to a global SOBJECT. Now I want to access the field in the sObject which was predefined in the Query. 

 

Query saved in CustomSetting: "login_cred " field "Soqlogin" = "SELECT Id,Registration_Approved__c,SiteProfile__c,SiteProfile__r.Name__c,SiteProfile__r.Default_Home_Page__r.Name__c FROM Contact WHERE UserName__c = username.toLowerCase() AND Password__C = :password "

 

global static SObject currentContact;

List<login_cred__c> logcredlist =[SELECT soqlogin__c FROM login_cred__c LIMIT 1];
string logcred = logcredlist[0].soqlogin__c;

currentContact = Database.query(logcred);

String profileName = currentContact.SiteProfile__r.Name__c;

 

 

Here am getting an error something like :"Save error: Field expression not allowed for generic SObject " 

 

Thanks in advance.

Sathya.S

Best Answer chosen by Admin (Salesforce Developers) 
Ranu JainRanu Jain

To ger relationship field from generic sObject like this - 

 

SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
String accountName = String.valueOf(c.getSObject('Account').get('Name'));
System.debug(accountName);

With custom relationships you'd use soemthing similar to:

s.getSObject('Your_Custom_Object__r').('Some_Field__c')

 

 

All Answers

Prafull G.Prafull G.

Thats correct! You can not access fields directly using sObject. You can typecast it or use sobject method get() to retrieve the value.

 

For your code, I can not see any specific reason to use sObject. You can directly use Contact type.

 

for example

 

global static Contact currentContact;

 

Try it and let us know if it helps.

 

NOTE: If you want to use sObject then You can not get values of relationship fields using sObject get method. i.e. currentContact.get('Registration_Approved__c') will work but currentContact.get('SiteProfile__r.Name__c') will not work.

 

Cheers!

sathya_sam3sathya_sam3

Thanku crmtech21.

Now am stuck up with the same. I am getting the direct field. but am not getting the value of relationship field in SObject :"CurrentContact" ..... i want to access the relationship field. Is there any other way? 

And i can't Use Contact directly as i want it to be a variable and change it to another object in future whenever I want from Custom Settings.

Ranu JainRanu Jain

To ger relationship field from generic sObject like this - 

 

SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
String accountName = String.valueOf(c.getSObject('Account').get('Name'));
System.debug(accountName);

With custom relationships you'd use soemthing similar to:

s.getSObject('Your_Custom_Object__r').('Some_Field__c')

 

 

This was selected as the best answer