0

I have the following lines of code

    List<SObject> sObjectList =[SELECTId,Name,SerialNumber,Product2Id,Product2.Name,Quantity,Status,AccountId,Account.Name,Parent.SerialNumber From Asset Where AccountId = 'some account id' LIMIT 1000];
    for (sObject sObj: sObjectList) {
        sObject sObjProd2 = sObj.getSObject('Product2');
        String prodName = (String)sObjProd2.get('Name');
        sObject sObjParent = sObj.getSObject('Parent'); 
        String parentSrNo = (String)sObjParent.get('SerialNumber');
     }

The above query works fine and it returns me the following data

[{
    "Id": "02i46000000YeKNAA0",
    "Name": "Asset 2",
    "SerialNumber": "6789",
    "Product2Id": "01t460000012C6JAAU",
    "Quantity": 1.00,
    "Status": "Registered",
    "AccountId": "0014600000DWUKLAA5",
    "Product2": {
        "Name": "GenWatt Diesel10kW",
        "Id": "01t460000012C6JAAU"
    },
    "Account": {
        "Name": "Test1",
        "Id": "0014600000DWUKLAA5"
    },
    "Parent": {
        "SerialNumber": "9812",
        "Id": "02i46000000YeYcAAK"
    }
}]

But when I execute line #5(sObject sObjParent = sObj.getSObject('Parent');), I get the following error:

System.SObjectException: Invalid relationship Parent for Asset

How can I get the value of Parent.SerialNumber in Apex?

1

You don't need to access this data dynamically. Static access should work just as well:

for (Asset record : [SELECT ... FROM Asset WHERE ... LIMIT ...])
{
    String serialNumber = record.Parent.SerialNumber;
}
  • Thank you Adrian for the response. Static access will not work for me as at the run time only I am getting to know the name of the field that I need to fetch the value for. SerialNumber was just an example. Field names are coming from the fieldset on Asset and user can add any field to the field set. I will know about it only at the run time. Hence, I have to access this data dynamically. – Guri May 23 '17 at 20:10

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.