Sort Order of Child Records Using a Standard Controller

Does anybody know of a way to order child records when accessed using a StandardController and displayed with an <apex:repeat> loop?

My guess is that it can’t be done and I need an extension, custom controller or to use a related list but the question is simply regarding whether this is possible.

e.g.

<!-- List these in order of created date -->
<apex:repeat value="{!Account.Contacts}" var="c">
</apex:repeat>

Answer

I don’t think there is anything like a setting or attribute to control that. There’s an idea for <apex:repeat> with control over sort order.

If you absolutely cannot use an extension, you could resort back to JavaScript.

<apex:page standardController="Account" >
    <apex:outputText value="{!Account.Name}"/><br/>
    <div id="contacts"></div>

    <script type="text/javascript">
      var contacts = [];
      <apex:repeat value="{!Account.Contacts}" var="c">
          contacts.push({
              Name : "{!c.Name}",
              CreatedDate : new Date("{!c.CreatedDate}"),
              toString : function() { 
                  return this.CreatedDate + ', ' + this.Name; 
              }
          });
      </apex:repeat>

      contacts.sort(function(con1, con2) {
          var comp = con1.CreatedDate - con2.CreatedDate;
          if (comp > 0) {
             return 1;
          }
          if (comp < 0) {
             return -1;
          }
          return 0;
      });
      // ...update the dom as desired...  
    </script>
</apex:page>

Attribution
Source : Link , Question Author : Matt Lacey , Answer Author : Peter Knolle

Leave a Comment