0

I have this query: List<sobject> query_result = Database.query(query);

with query = SELECT Email,Fax,(SELECT Status,Type FROM Cases),(SELECT CreatedDate FROM Tasks)FROM Contact WHERE Id =

How can I browse all results (Cases, Tasks , Contact) to store them separately in new lists?

6

To access the related lists you first need to cast the generic SObject type to the correct type:

List<Contact> contactList = new List<Contact>();
for (SObject sob : query_result) {
    Contact c = (Contact) sob;
    contactList.add(c);
    List<Case> caseList = c.Cases;
    List<Task> taskList = c.Tasks;
    // Do whatever you want here with the lists
}

Bear in mind that you will have a separate list of cases and tasks per contact.

You don't explain why you are using a dynamic query; it would be simpler to just use static SOQL:

List<Contact> contactList = [select ... from Contact ... where ...];
for (Contact c : contactList) {
    List<Case> caseList = c.Cases;
    List<Task> taskList = c.Tasks;
    // Do whatever you want here with the lists
}

PS

If you want to avoid any specific types and just use SObject methods:

for (SObject sob : query_result) {
    List<SObject> caseList = sob.getSObjects('Cases');
    List<SObject> taskList = sob.getSObjects('Tasks');
    // Do whatever you want here with the lists
}
|improve this answer|||||
  • Thanks. I'm using dynamic query because I'm building app where user choose fields for a SObject & children, I store choices and I have to query and display results in vfp – Amine Darkaoui Nov 13 '14 at 12:55
  • @AmineDarkaoui Makes sense. Just wanted to ask because sometimes dynamic SOQL is used where static SOQL would be better. – Keith C Nov 13 '14 at 12:57
  • Is it possible to replace c.Cases with c.get('Cases') so I can dynamically get all the child fields without using static declaration. – Amine Darkaoui Nov 13 '14 at 14:52
  • @AmineDarkaoui Yes there is an SObject.getSObjects method that does that. There are several other methods that you may find useful too so take a look at the sObject Class documentation. So if you want to you can implement the whole thing without explicit types. See the added "PS". – Keith C Nov 13 '14 at 14:55

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.