Retrieve Topics based on custom field?

UPDATE: I think I’ve got it (mostly) working (!). Now, this will show the “latest” topics matching the custom field value. (the #latest method was the closest one I could find that made sense in the config/routes.rb file).

It’s important that, in fact, all topics that have the relevant custom field fun_level value are loaded onto the page. Is there something else I need to do to make that happen?


Here’s the code for my own notes and in case helpful to others:

–I’ve created the custom field :fun_level. Then:

plugin.rb

TopicQuery.add_custom_filter(:fun_level) do |topics, query|
  if query.options[:fun_level]
    topics.where("topics.id in (
      SELECT topic_id FROM topic_custom_fields
      WHERE (name = 'fun_level')
      AND value = '#{query.options[:fun_level]}'
    )")
  else
    topics
  end
end

/connectors/my-plugin-outlet/fun-level.js.es6 (a javascript file that is activated when going to relevant page. So this javascript could be in an initializer or in a connector linking up to a plugin outlet. I like to use code that goes with a connector, so I’ll use setup component here):

const ajax = require('discourse/lib/ajax')

export default {
    setupComponent(args, component) {
      let parsedResultArray = []
      var endPoint = '/latest?fun_level=' + funLevel  //funLevel = variable with value from the params   
      ajax(endPoint).then(function (result) {
            console.log('topic list result for topics matching that fun level = ')
            console.log(result.topic_list.topics)
            //parse results, and load them into parsedResultArray
            component.set('showTopics', parsedResultArray        
      })
   }
}

Now, the topics will be loaded into the {{topic-list topics=showTopics}} I have in the corresponding component, that’s put in the template through my-plugin-outlet.

This is a big step forward. Thank you very much, @angus.

4 Likes