Create a new topic button with category and topic template

For a PM you’d need to set a few of the composer options differently.

Something like this:

(Same as above, in a theme component in the </head> section)

<script type="text/discourse-plugin" version="0.8.18">
api.decorateWidget("header-buttons:after", helper => {
  if (Discourse.User.current()) {
    
    // edit these two to your liking
    var $ntb_text = "New Personal Message",
      $ntb_icon = "heart",
        
      // no need to edit these
      $ntb_icon_class = ".fa-" + $ntb_icon,
      $ntb_button_class = "btn btn-default btn btn-icon-text",
      $ntb_button_helper = "button#new-create-topic-custom",
      $ntb_icon_helper =
        "i.fa" + $ntb_icon_class + ".d-icon .d-icon-" + $ntb_icon,
      $ntb_label_helper = "span.d-button-label";

    const createPM = function() {
      const container = Discourse.__container__,
        Composer = require("discourse/models/composer").default,
        composerController = container.lookup("controller:composer");

      composerController.open({
        action: Composer.PRIVATE_MESSAGE,

        // 1- set recipients (Case Sensitive) or comment the line below
        usernames: "discobot,john,mike",

        // 2- set title or comment the line below
        topicTitle: "Title",

        // 3- uncomment the line below to set a "template" for PM.
        // Not really recommended will
        // override any drafts everytime the 
        // button is pressed 
        
        // topicBody: "placeholder content",

        // no need to change these
        archetypeId: "private_message",
        draftKey: Composer.NEW_PRIVATE_MESSAGE_KEY,

      });
    };

    return helper.h(
      $ntb_button_helper,
      {
        className: $ntb_button_class,
        title: $ntb_text,
        onclick: createPM
      },
      [helper.h($ntb_icon_helper), helper.h($ntb_label_helper, $ntb_text)]
    );
  }
});
</script>

Obviously, if you plan on using all three buttons you can reduce the size of the code quite drastically because most of it is shared by all three, but I kept things separate because some might just want to use one and not all three.

What this will do is add a button to the header like so:

Clicking the button will open the composer and the fields will be pre-filled with whatever you chose:

I already left a comment in the code about setting any placeholder content in the body for PMs using this method. It’s not recommended unless you have a very specific template. This will override any previously saved PM drafts everytime you use the button.

That’s why it’s “off” by default in the code above.

I’ve tested this a bit and have not seen any problems. If you encounter anything let me know.

11 Likes