How to add action for button in plugin

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() {
      ...
    }
  }
};
2 Likes

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

7 Likes

Thanks Joe, it works like a charm!

3 Likes