I have a visualforce email that show all case comments within a case. I'd like to sort the comments by created date (which is one of the columns). How can I achieve that?

    <messaging:emailTemplate recipientType="User"
    subject="Case #{!relatedTo.CaseNumber} is Closed"
    replyTo="myemail" >

<messaging:htmlEmailBody >        
         <STYLE type="text/css">
               TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center } 
               TD  {font-size: 11px; font-face: verdana } 
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
                  <font face="arial" size="2">
        <p>case<b> {!relatedTo.CaseNumber}</b> was closed </p>
        <br/>Account: <b> {!relatedTo.Account.name}  </b>  
        <br/>Case Owner: {!relatedTo.owner.name}
        <br/>Below is a list of Case Comments related to this case

       <table border="0" >
                 <tr > 
                     <th>Comments</th><th>Created Date</th><th>Public</th> <th>Created By</th>
    <apex:repeat var="opp" value="{!relatedTo.CaseComments}">
       <p />

<messaging:plainTextEmailBody >

Below is a list of Case Comments related to the Case: {!relatedTo.CaseNumber}

Account: {!relatedTo.Account.name}
Opportunity Owner: {!relatedTo.owner.name}

[ Comments ] - [ Created Date] - [ Public ]

<apex:repeat var="opp" value="{!relatedTo.CaseComments}">
[ {!opp.CommentBody} ] - [ {!opp.CreatedDate}  ] - [ {!opp.IsPublished} ]



You could use a Visualforce Component to requery the CaseComments in the order you desire:


<apex:page standardController="Case">
  <apex:sectionHeader title="{!Case.Subject}" />
  <c:sortedCaseComments caseId="{!Case.Id}" />


<apex:component controller="SortedCaseCommentsController">
  <apex:attribute name="caseId" type="Id" assignTo="{!AttributeCaseId}" description="Case Id" />

  <apex:dataList value="{!CaseComments}" var="caseComment">
    {!caseComment.Id} - {!caseComment.CommentBody}


public class SortedCaseCommentsController {
  public Id     AttributeCaseId    {get; set;}

  public List<CaseComment> getCaseComments() {
    return [
      SELECT CommentBody
      FROM CaseComment
      WHERE ParentId = :this.AttributeCaseId
      ORDER BY CreatedDate DESC


sorted case comments

| improve this answer | |
  • herp, missed your component declaration and attribute off, also don't you want to sort your SOQL? – Phil Hawthorn Mar 12 '13 at 18:39
  • Thanks @user320! could you post the test coverage for this controller? – Itay B Mar 14 '13 at 9:05

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.