0

So I need to access the value of an email field which is set by a workflow. However this needs to be done through a lookup relasionship as seen below.

Customobj1__c newRecord = new Customobj1__c();
newRecord.populatefields = 'ect';

sObject newobject;
newObject = newRecord;

Customobj1__c (child) has a lookup relasionship to Customobj2__c (parent). So if I want to get a value of Customobj2__c field I do the following

newRecord.customRelasionship__r.obj2Field__c;

To access a value of a field in Apex I use the following (for picklist field):

 Schema.sObjectType objType = objObject.getSObjectType();
 Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
 map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();
 list < Schema.PicklistEntry > values =
   fieldMap.get(fld).getDescribe().getPickListValues();     

The issue I am having is since I have a lookup relasionship, I cant use the sObject methods. I believe I need to specify that the sObjectType is of Customobj2__c (to access the email field) and then cast it back to sObject to use the rest of the methods. Once I have a map of all the fields in Customobj2__c, I can use fieldMap.get(emailfield__c) but how do I actually obtain the value in this field?

I tried the following but it says getSObjectType() is not recognized since its of type Customobj1__c and not sObject

((Customobj1__c)newObject).customRelasionship__r.obj2Field__c.getSObjectType(); 
  • The picklist code which you have shared is used to get the Metadata of picklist field while in current case you need the actual data of email field. So you need a SOQL and then get the data. – Tushar Sharma Feb 14 '18 at 12:11
1

The picklist code which you have shared is used to get the Metadata of picklist field while in current case you need the actual data of email field. So you need a SOQL and then get the data.

If you dynamically want to access the data then you need getSobject to traverse up in relationship.

sObject sob = [SELECT customRelasionship__r.obj2Field__c FROM Customobj1__c LIMIT 1];
String email= (String) sob.getSobject('Customobj2__c').get('Email__c');
System.debug(email);
  • I get this error: FATAL_ERROR System.SObjectException: Invalid relationship Customobj2__c for Customobj1__c when i run my code. Any ideas? – M guy Feb 14 '18 at 14:12
  • please open new posts with any new problem you are facing rather then following up in comments. thanks – glls Feb 14 '18 at 14:22

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.