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    
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.