Call a widget action from another widget

AI-generated summary

lcor sought to trigger the toggleSearchMenu action from a custom button widget to open the search menu, but encountered an error: toggleSearchMenu not found. Attempts using sendWidgetAction, action, and onclick within the widget’s html method failed. After experimenting, lcor found a working solution by importing the header widget via createWidgetFrom and accessing the toggleSearchMenu action through its scope. This approach successfully enabled the desired functionality. The user shared their code and expressed gratitude for the resolution.

Hello,

I would like to call the toggleSearchMenu action from a custom button widget that would open the search menu by clicking it.

I tried:

  click() {
    this.sendWidgetAction('toggleSearchMenu').then(() => console.log("SENDWIDGETACTION"));
  }

But when clicking my button, it says toggleSearchMenu not found in the console.

I tried other Not working ways as you can see here:

import { createWidget } from "discourse/widgets/widget";
import { iconNode } from "discourse-common/lib/icon-library";
import { h } from 'virtual-dom';

export default createWidget("search-btn-widget", {
  tagName: "div.search-btn-widget",
  buildKey: () => "search-btn-widget",

  html(args) {
    let search_button_helper = "button#search-btn";
    let search_button_class;
    let search_title = "Chercher un sujet";
    let search_text = "Chercher un sujet";
    let search_icon = "ri-small-recherche";
    let search_label_helper = "span.d-button-label";

    if (args == "default") {
      search_button_class = "btn btn-default btn btn-icon-text";
    } else if (args == "primary") {
      search_button_class = "btn btn-primary btn btn-icon-text";
    } else {
      return;
    }

    const toggleSearch = function() {
      this.sendWidgetAction("toggleSearchMenu");
    };

    return h(
      search_button_helper,
      {
        className: search_button_class,
        title: search_title,
        // action: "toggleSearchMenu" => Not working
        // onclick: "toggleSearchMenu" => Not working
        onclick: toggleSearch
      },
      [iconNode(search_icon), h(search_label_helper, search_text)]
    )
  },
  // click() {
  //   this.sendWidgetAction('toggleSearchMenu').then(() => console.log("SENDWIDGETACTION"));
  // } => Not working
});

Any idea on how I could call this widget action inside my widget if that’s something possible?

Thanks a lot :pray:

Found a solution, using createWidgetFrom and importing header widget:

import {
  default as header
} from "discourse/widgets/header";

So that made me able to access the action method toggleSearchMenu scope.