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
Sandrine94748Sandrine94748 

Get the value of custom field using sObject

Hello,

I am trying to get a value of custom field using sObject.
Can someone help me with this
          sObject sObj = new QuoteLineItem();

           for (QuoteLineItem q : qli){
               sObj = q;
				
               System.debug('$$$'+q.Product2.Obj1__r.cf1__c);  //output is TRUE as field is a boolean
               System.debug('$$$'+String.valueOf(q.Product2.Obj1__r.cf1__c)); //output is TRUE 
               System.debug('$$$'+string.isNotBlank(String.valueOf(q.Product2.Obj1__r.cf1__c)));  //output is TRUE
               if(string.isNotBlank(String.valueOf(sObj.get(fieldToCompare)))) { //ERROR: Invalid field Product2.Obj1__r.cf1__c)
                   //Do something
			   }	             
            }

I am obliged to use SObject as i have specific use case.
I just want to get the value of Product2.Obj1__r.cf1__c using sObject.
i am able to retrive it using q.Product2.Obj1__r.cf1__c but as in sObject, there is missing q, this can be the reason it is not retriving.

thanks for suggestion 
Best Answer chosen by Sandrine94748
PawanKumarPawanKumar
Please take a look at below example. Here i am trying toget Account.Name
SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1'); String accountName = String.valueOf(c.getSObject('Account').get('Name')); 

So in your case, it should be something like below. Please take care parenthesis.
String.valueOf(((c.getSObject('Product2')).getSobject('Obj1__r')).get('cf1__c')); 

All Answers

PawanKumarPawanKumar
Please take a look at below example. Here i am trying toget Account.Name
SObject c = Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1'); String accountName = String.valueOf(c.getSObject('Account').get('Name')); 

So in your case, it should be something like below. Please take care parenthesis.
String.valueOf(((c.getSObject('Product2')).getSobject('Obj1__r')).get('cf1__c')); 
This was selected as the best answer
Sandrine94748Sandrine94748
Hello Pawan,
Its the perfect answer i was looking for.

Is it possibel to guide me incase of put.
 
sObject sObj = new QuoteLineItem();
    sObject sOj = new ContractLineItem();

     for (QuoteLineItem q : qli){
         sObj = q;
         String fieldToCompare = 'cf1__c';
         sOj.put(fieldToCompare, sObj.getSobject('Product2').getSobject('Obj1__r').get(fieldToCompare));
      }


 
PawanKumarPawanKumar
Hi Kiran,
As far i know, you can not update relationship like that. You have to update relationship separately by usng update dml, that's what i know. But you can post this as a separate question. May be other can help you for the same.

Regards,
Pawan Kumar