Specify parameters for menu functions
Asked Answered
S

2

9

This is a snippet in the Google Apps Script for adding a menu in Google Docs/Forms/Sheets. As stated in the Menu#addItem method it calls the menuItem2 function, but the snippet didn't include a sample on how to call the addItem when you want to add parameters in function call, or is this not possible?

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
    .addItem('First item', 'menuItem1')
    .addSeparator()
    .addSubMenu(ui.createMenu('Sub-menu')
      .addItem('Second item', 'menuItem2'))
    .addToUi();
}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('You clicked the second menu item!');
}

function menuItem2(PARAMETER_HERE) {
  // codes    
}
Stela answered 10/9, 2014 at 5:50 Comment(0)
A
7

You can't add parameters to functions called by a menu.

A simple workaround is to store parameters elsewhere (in scriptProperties for example) and read these parameters if parameter is undefined.

function menuItem2(PARAMETER) {
  // if PARAMETER is undefined then read default parameter in scriptProperties
  // codes    
}

In this configuration you can call the menuItem2 function from elsewhere in the script using a "normal" parameter and it will be handled as expected.

Apospory answered 10/9, 2014 at 6:4 Comment(0)
O
0

You may pass static parameters. Moreover, you can even create a dynamic menu.

class DynamicMenu {
  constructor() {      
  const mySimpleParams = [["one", "1"], ["two", {aa: "objectparam"}], ["three", [["arrayParam"]]]]

  this.createMenu = (ui) => {
    const menu = ui.createMenu('My menu')
      mySimpleParams.forEach(param=>{
          //beware to name without strange characters
          const functionName = `function${param[0]}`
          const entryName =  `option-${param[0]}`
          menu.addItem(entryName, `menuActions.${functionName}`)
      })
     menu.addToUi();
  }
  
  this.createActions = () => {
      const menuActions = {}
      mySimpleParams.forEach(param=>{
          const functionName = `function${param[0]}`
          menuActions[functionName] = function() {mayParametrizedFunction(param[1])}
      })
      return menuActions;
  }

  function mayParametrizedFunction(param) {
         SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
               .alert(`Got you folk!: ${param}`);
  }
 }
}

const menu = new DynamicMenu();
const menuActions = menu.createActions()

function onOpen() {
  menu.createMenu(SpreadsheetApp.getUi())
}
Oulman answered 3/12, 2022 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.