3

I'm creating a dynamic custom menu from REST call in google spreadsheet. With every call I receive different sports that I want to use as menu items

  // sample sports array
  var menuItemsArr = ['Footbal', 'Tennis', 'Swimming'];

  var menu = SpreadsheetApp.getUi().createMenu("Sports");
  for (i in menuItemsArr){
      menu.addItem(menuItemsArr[i],'createSheet')
       .addSeparator()
  }
  menu.addToUi();

When the user clicks on menu item I want to create a new sheet with title - the sport that was clicked. So if the user choose Tennis I want to create a sheet with name Tennis.

Is it possible to know which menu item was clicked (to take the name of the item (Tennis) somehow, or at least the index of the menu item that was clicked?

Any help will be appreciated! Thanks.

tehhowch
  • 9,645
  • 4
  • 24
  • 42
kmignt
  • 67
  • 14
  • It's not possible at the moment, here's feature request, you can "star" it: https://issuetracker.google.com/issues/36753036 For now you can just create one function for each menu item (`createSheetFootbal`, `createSheetTennis`, ..): `menu.addItem(menuItemsArr[i],'createSheet'+menuItemsArr[i]);` – Kos Jun 20 '18 at 11:08
  • I'm afraid that this is not possible. How I said - my data is always dynamic. I cannot create functions for every menu item. Thanks anyways – kmignt Jun 20 '18 at 11:57
  • This might be helpful for your case: https://stackoverflow.com/questions/23823558/google-apps-script-calling-a-function-from-menu-with-a-spreadsheet-range-as-the Construct array `entries` of objects with `name` and `functionName` keys – Kos Jun 20 '18 at 13:16
  • Perhaps you could use a dialogue or a side bar and a select – Cooper Jun 20 '18 at 13:47
  • Thanks everyone. In the end I used dropdown list. – kmignt Jul 18 '18 at 05:58
  • Even if you could get the call stack (which you can), the spreadsheet calls the menu function at the top of the stack. You don't see anything that happens before menu function is called, unfortunately. – toddmo Feb 08 '20 at 17:52

1 Answers1

1

Google Apps Script .createMenu and .createAddonMenu are able to call functions by their name as string and only looks for functions with that name on the Apps Script project global scope.

The alternative is to create your user interface by using a dialog or sidebar with the HTML Service.

Rubén
  • 34,714
  • 9
  • 70
  • 166