How to get category info from composer?

Is it possible to run some code (from a theme component) when a category is selected in the composer? I’m interested in getting what category is selected both when the composer just been opened and when the category dropdown has been changed.

Was thinking that it perhaps could be possible by modifying a controller or a component, like the composer controller. But wasn’t able to find the category info…

2 Likes

You can observe model.categoryId in the composer controller and run you code when the change occurs.

5 Likes

Thanks @fzngagan!

A follow up question, never observed any model before :slight_smile: . I came up with the following that appears to work.

const { observes } = require('discourse-common/utils/decorators');
api.modifyClass("controller:composer", {
    @observes('model.categoryId')
    getCategory() {
        let categoryId = this.get("model.categoryId");
        if (categoryId == null) return;
        
        let category = this.site.categories.findBy("id", categoryId).name;
    }
});

Is that the right way (or preferred way) to do it? And is that the best way to get the category name from the id?

1 Like

You can check what the model object contains. It might have category name in there already.

1 Like

With “model object”, do you mean that I should do something like this right?

this.get("model"))

Edit:
Anyhow, the code works great. Thanks again!

1 Like