Find your content:

Search form

You are here

get parent object record sorted by child object field

 
Share

I have created one vf page on which I am showing records from parent object along with one date field on child object. For eg. Job(parent) and its taks(child), I am showing job details with one of its latest task's date. Now I wanted to sort this list of records by the task date on child object. How can I do that?

Thank you in advance.


Attribution to: Rahul Nagardalekar

Possible Suggestion/Solution #1

Another possibility is to reorder the list by querying the child object using the MAX aggregate function, ordering by the MAX date. This could be useful if you cannot or do not want to refactor other code to use a wrapper class and comparable.

This code assumes that you already have a List of Parent__c objects, along with the related child list containing the single record that has the latest date. The AggregateResult query selects the maximum date for each parent and orders the results by that maximum in descending order (i.e., greatest date first).

// This already exists somehow
List<Parent__c> theParents = getParentsAndSingleChildRecSomehow();

theParents = sortByChildDate(theParents);

private List<Parent__c> sortByChildDate(List<Parent__c> parents) {
    Map<Id, Parent__c> parentMap = new Map<Id, Parent__c>(parents);
    List<Parent__c> retList = new List<Parent__c>();

    for (AggregateResult aggRes : [
         SELECT MAX(Date__c), Parent__c parentId
         FROM Child__c
         WHERE Parent__c IN :parentMap.keySet()
         GROUP BY Parent__c
         ORDER BY MAX(Date__c) DESC
    ]) {
        Id parentId = (Id) aggRes.get('parentId');
        retList.add(parentMap.get(parentId);
    }
    return retList;
}

Attribution to: Peter Knolle

Possible Suggestion/Solution #2

If I were you I would use:

Wrapapper class:

https://developer.salesforce.com/page/Wrapper_Class

and comparable interface:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_comparable.htm

Or If it Parent object is master you could create roll-up summary field.


Attribution to: Artur Kępczyński
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34635

My Block Status

My Block Content