How to add action for button in plugin

AI-generated summary

User wyudong is creating a Discourse plugin to display a button and perform a custom action. They have successfully displayed the button but are experiencing an error “had no action handler for: submitContent” when trying to create the custom action in actions.js.es6. Johani suggests renaming the file to button.js.es6 to match the .hbs file name, as both files in a connector class should have the same name. This solution works for wyudong.

I want to make a plugin to show a button and do some action. The button can already be displayed at the desired place, but I don’t know how to create a custom action for it. The file structure is like followings:

plugins/discourse-my-plugin
├── assets
│   ├── javascripts
│   │   └── discourse
│   │       ├── initializers
│   │       │   └── my-plugin.js.es6
│   │       └── templates
│   │           └── connectors
│   │               └── user-messages-nav
│   │                   ├── actions.js.es6
│   │                   └── button.hbs
├── config
└── plugin.rb

initializers/my-plugin.js.es6

import { withPluginApi } from "discourse/lib/plugin-api";

function initializeButton(api) {
  api.decoratePluginOutlet('user-messages-nav', (elem, args) => {
    ...
  });
}
export default {
  name: "my-button",
  initialize() {
    withPluginApi("0.8.31", initializeButton);
  }
};

button.hbs

{{d-button class="btn-primary" action="submitContent" label="submit_content"}}

Is it correct to create my custom action like this in actions.js.es6? The error is “had no action handler for: submitContent” but how can I fix it?

export default {
  actions: {
    submitContent() {
      ...
    }
  }
};

You were very close :+1:

You only need to change the file name. Both the .hbs and js.es6 files in your connector class need to have the same name. So, if you change

actions.js.es6

to

button.js.es6

it should work. You can read more about connector classes here

Thanks Joe, it works like a charm!