1

So, I've been struggling with this for a few hours now and I think I need a different pair of eyes which I have a feeling will be able to tell me my mistake in a flash!

I've queried for some data as such:

public String returnSOQL()
{
    string SOQLquery = 'SELECT Id, Name, Date_Registered__c, Project__r.Id, Project__r.Name';

    return SOQLquery;
}

And casted this to an sObject called RAIDObject.

I'm trying to access this data like so:

public id ProjectID
{
    get { return (string)RAIDObject.get('Project__r.Id'); }
}

Can I not use the get function to retrieve dynamic relationship data on a generic sObject in this way? If I try to do this non dynamically this can't obviously be done from a generic object type such as sObject.

Any help much appreciated.

1

The first function returns a plain string, not a database query.

Assuming you are later doing a query, then you need to use a combination of getSObject and get:

(Id)RAIDObject.getSObject('Project__r').get('Id');

A few notes, however:

You really should use the Id type when the data type is an Id. An Id is like a String, but has "magical" properties.

You really should prefer to use "Project__c" instead of "Project__r.Id". While they are the same value, one requires more overhead, and if Project__r happens to be null, the code above would cause an exception-- in other words, you'd have to add an additional null check if you weren't sure that a value was populated:

(Id)(RaidObject.getSObject('Project__r') == null? null: RaidObject.getSObject('Project__r').get('Id'));
  • You are spot on, it works brilliantly. I had variations of your answer including user getSObject and separation of object get requests but never the two together! This is perfect. Also yes thankyou for being so specific and taking the time to go further with your teaching. I did have these checks in and I really should of added them in to my code but I was trying to confine the problem to it's context only! Thank's anyway though and it will be very helpful for other users I'm sure. – MattGarnett Feb 11 '16 at 17:32

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.