This is a question about the isSet function on SObjects. Compare a similar question from 2019 here, but the discussion did not go beyond OwnerId.
In my case, Apex gets a QuoteLineItem from a query (in reality dynamic SOQL) like
QuoteLineItem qli = [SELECT Product2Id FROM QuoteLineItem LIMIT 1];
I want to conditionally avoid execution of the following line (and a bunch of other references to Product fields) to avoid "System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: QuoteLineItem.Product2":
String s = qli.Product2.Name;
For a custom child object of Product2 the following isSet
returns true
...
ProductChild__c child = [SELECT Product__r.Name FROM ProductChild__c LIMIT 1];
System.assert(child.isSet(ProductChild__c.Product__c));
... and it returns false
, when the lookup is not in the SELECT.
But is isSet
of any use in my case?
I've tried different flavors of isSet for the Product2.Name reference:
// field version
System.assert(qli.isSet(QuoteLineItem.Product2Id)); // passes, but unhelpful
System.assert(qli.isSet(QuoteLineItem.Product2.Id)); // passes, but unhelpful
System.assert(qli.isSet(QuoteLineItem.Product2.Name)); // does not save to Salesforce
System.assert(qli.isSet(QuoteLineItem.Product2)); // does not save to Salesforce
// String version
System.assert(qli.isSet('Product2Id')); // passes, but unhelpful
System.assert(qli.isSet('Product2.Id')); // System.SObjectException: Invalid field: Product2.Id
System.assert(qli.isSet('Product2.Name')); // System.SObjectException: Invalid field: Product2.Name
System.assert(qli.isSet('Product2')); // System.SObjectException: Invalid field: Product2
(This shows for a trigger context isSet
returns more often false
than intuitive, but above tests never see false
anyway.)
Is there a correct form?
ProductChild__c
example. Or have I missed something?