Pulsante crea nuovo argomento con categoria e modello di discussione

Sto esaminando il seguente tema come riferimento.

Il mio obiettivo è trovare un modo per aggiungere un secondo pulsante “Nuovo argomento” visibile solo ai membri di un gruppo specifico. Questo gruppo ha accesso a un’area privata del forum e vorrei che il pulsante in questione avvii un nuovo argomento in quella sezione, indipendentemente dalla pagina in cui si trovano. Vorrei inoltre utilizzare un modello di argomento o una funzionalità simile di testo predefinito con questo pulsante. Credo di aver capito come aggiungere selettivamente il pulsante in base alla classe del gruppo principale presente sul tag body, ma al momento non sono ancora abbastanza pratico da inserire del testo predefinito (o un modello di argomento) nei nuovi argomenti creati con questo secondo pulsante. Qualcuno ha qualche suggerimento?

4 Mi Piace

È possibile. Devi prima preparare la tua categoria con un modello di argomento. Vai alla categoria che desideri utilizzare e modifica il suo modello di argomento come mostrato qui:


Quindi scopri l’ID della categoria. Puoi farlo visitando your.site.com/categories.json

Qui su meta appare così:

Probabilmente esiste un modo migliore per trovare il categoryId, ma questo funziona come necessario in questo caso.

Ora, supponiamo di voler utilizzare la categoria bug. L’ID corrispondente sarebbe “1” in base a /categories.json.

Per #feature, sarebbe “2” e così via.


Ora che hai l’ID e la categoria dispone di un modello di argomento, puoi copiare il codice dal tema, apportare alcune modifiche e aggiungerlo a un componente tema separato.

Ho già apportato le modifiche qui, quindi puoi semplicemente copiare questo codice e modificare i valori come necessario:

<script type="text/discourse-plugin" version="0.8.18">
api.decorateWidget("header-buttons:after", helper => {
  if (api.getCurrentUser()) {
      
    // modifica queste due righe secondo le tue preferenze
    var $ntb_text = "testo del pulsante",
      $ntb_icon = "plus",
      
      // non è necessario modificare queste righe
      $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 createTopicCustom = function() {
      const container = Discourse.__container__;
      const Composer = require("discourse/models/composer").default;
      const controller = container.lookup("controller:navigation/category");
      const composerController = container.lookup("controller:composer");

      composerController.open({
        action: Composer.CREATE_TOPIC,
        draftKey: Composer.DRAFT,

        // imposta l'ID della categoria qui sotto
        // consulta site.com/categories.json
        // come riferimento
        categoryId: 3
      });
    };

    return helper.h(
      $ntb_button_helper,
      {
        className: $ntb_button_class,
        title: $ntb_text,
        onclick: createTopicCustom
      },
      [helper.h($ntb_icon_helper), helper.h($ntb_label_helper, $ntb_text)]
    );
  }
});

</script>

Questo va inserito nella sezione <head> sotto “Common”.


Una volta completato, dovresti ottenere qualcosa di simile a questo: (ho aggiunto dei margini con CSS)

Cliccando sul nuovo pulsante si aprirà il compositore con la categoria selezionata e il modello di argomento della categoria sarà presente.

Presumo che questo sia tutto ciò di cui hai bisogno, basandomi su:

16 Mi Piace

Thanks Joe. I’ve already found a use for your instructions above. Very helpful.

Do you know how to create a PM, rather than posting into a category?

eg: Is there a CategoryID specifically for PM messages?

1 Mi Piace

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 Mi Piace

Love it. Worked perfectly. Thanks Joe, you’re awesome!

I noticed the user names are case sensitive. If a username’s case is wrong, the name appears in the recipient list, but the PM won’t send. Suggest you add this to your comments: -

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

Hi @Johani - thank you, I have implemented this, but a bit too successfully!

Would it be possible to make a new personal message header button appear only selectively for those who have access to personal messaging? New users by default don’t have access to PM so should not see this button…

We have set the site setting (for our TL0, TL1 and TL2 users (who therefor are restricted from personal messaging))

Thanks again,

1 Mi Piace

Hi @jerry0

Yes, that is possible!

One way to do this is to look up the current user’s trust level and use that as a base to determine whether or not to create the PM button.

You would use something like this:

<script type="text/discourse-plugin" version="0.8.18">
// no need to edit these
const container = Discourse.__container__,
  controller = container.lookup("controller:application"),
  trust = controller.get("currentUser.trust_level");

api.decorateWidget("header-buttons:after", helper => {
  // change desired trust level here
  if (Discourse.User.current() && trust >= "2") {
    // 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 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>
4 Mi Piace

Well that is fab. I will have to wait to get back from my travels tomorrow but will try it out then. Thanks!

2 Mi Piace

I’ve now tried it out and it works well. Many thanks.

1 Mi Piace

Is it only possible to do this if u are able to code?

Um, no - I really can’t :grinning:… just followed the instructions above…

Would it be possible to change the button text for the default + New Topic button based on which category you’re browsing?

2 Mi Piace

Yes, that would also be possible as well. You can use something like this in the header section of a theme component

<script type="text/discourse-plugin" version="0.8">
const i18nTopicLable = I18n.lookup("topic.create");
api.modifyClass("component:create-topic-button", {
  didInsertElement: function() {
    var button = $(this),
      category = button[0].parentView.get("category"),
      label = button[0].label,
      newTopicLabel = "topic.create",
      buttonText = "";

    if (category) {
      categoryName = category.name;

      if (label != newTopicLabel) {
        return;
      } else {
        switch (categoryName) {
          case "category1": // category name
            buttonText = "category1 text"; // button text
            break;
          // repeat
          case "category2":
            buttonText = "category2 text";
            break;
          // add more above this line
          default:
            buttonText = i18nTopicLable;
        }
        $("#create-topic .d-button-label").text(buttonText);
      }
    }
  }
});
</script>

To add new categories, you only need to add this above where it says default

case "category":
  buttonText = "text";
  break;

If you have a pending draft and the button says “open draft” the script won’t fire.

I’ve created a small preview on theme creator and changed the text for the movies, tech, school, videos and gaming categories

Edit:
@dax informed me that I had missed something in the snippet I posted previously and so I updated it and the preview so be sure to use the latest one @tophee

13 Mi Piace

Questo ha smesso di funzionare. Una nuova soluzione per rinominare il pulsante in base alla categoria è disponibile qui:

Procedura:

  1. Clona o scarica e decomprimi il componente del tema da GitHub - VaperinaDEV/category-btn-name · GitHub
  2. Modifica il file category-btn-name/locales/en.yml e inserisci i testi dei pulsanti che desideri utilizzare, ad esempio:
en:
  new_event: Nuovo evento
  new_deadline: Nuova scadenza
  1. Modifica il file category-btn-name/javascripts/discourse/api-initializers/initialize-btn-names.js per definire quale testo del pulsante utilizzare per quali categorie:
const TRANSLATION_KEYS = {
  "Events": "new_event",
  "Calendar": "new_event",
  "Deadlines": "new_dealine",
};
  1. Installa il componente del tema
2 Mi Piace