Forum Discussion

nickyates's avatar
nickyates
Mentor
12 years ago

sorting forum posts by the number of messages in each post

I am trying to make a custom component which displays the 3 forum posts with the most comments.  I am having trouble displaying the posts in decending numerical order of the number of comments each post has.  is there a way to do this using either the API or Freemarker?  Please could you provide an short example?  Thanks

  • YuriK's avatar
    YuriK
    Khoros Expert

    Hey nickyates,

     

    Here is a sample component I wrote to print out the id's of threads in descending order by the message count in the thread.

     

    <#assign thread_list=rest("/boards/id/Moderation/threads").threads.thread/>
    <ul>
    <#list thread_list?sort_by(['messages','count'])?reverse as thread>
    <li>${thread.id}</li>
    </#list>
    </ul>

     You should be able to get the topic message from each thread using thread.messages.topic.

     

    I hope this helps,

     

    Yuri

    • nickyates's avatar
      nickyates
      Mentor

      Hi Yuri,

       

      Now ive added some more activity to my board ive noticed that the ordering isnt quite right.  My top 5 boards are ordered by the number of messages as shown descibed in your code above however it is ordered as described below

       

      5

      3

      11

      1

      1

       

      I believe this is because the sort_by is assuming that the content of the count field is text.  In a previous thread (https://lithosphere.lithium.com/t5/developers-discussion/sorting-forum-posts-by-the-number-of-messages-in-each-post/m-p/83626#M2959) i added in the ?number command however when i do the same here it throws an error.

       

      Thanks 

       

      Nick

    • Hi,

       

      I am trying to sort posts by no. of views. How to do that .

       

      Just tried below code, based on YuriK solution, but it doesn't works :

       

      <#assign thread_list=rest("/boards/id/<board_ID>/threads").threads.thread/>
      <ul>
      <#list thread_list?sort_by(['messages','views','count'])?reverse as thread>
      <li>${thread.id}</li>
      </#list>
      </ul>   

      Thank you.

       

      Regards,

      Vishwajeet.

  • YuriK's avatar
    YuriK
    Khoros Expert

    The problem is that sort_by is not able to convert strings to numbers. And our DOM has all the items as strings. You can either do two pass-throughs like what we did in here, or you can try Adam's suggestion which I think is more elegant but requires 2 calls.

    Hope this helps,

    Yuri