google-apps-scriptgmail-addonsgoogle-apps-script-addon

Change the value for a Widget KeyValue Switch SetValue within Google App Script


I'm not understanding how to setValue for the switch. I want to be able to have an on/off using a users stored value.

Over at the Google Scripts CardService Switch Docs they have show this example:

var switchKeyValue = CardService.newKeyValue()
    .setTopLabel("Switch key value widget label")
    .setContent("This is a key value widget with a switch on the right")
    .setSwitch(CardService.newSwitch()
        .setFieldName("form_input_switch_key")
        .setValue("form_input_switch_value") // <-- note that part
        .setOnChangeAction(CardService.newAction()
            .setFunctionName("handleSwitchChange")));

When I try to setValue I never see the switch get toggled to an on state. I know that setValue needs to be a string, and I've tried the example above, and equally, I've tried:

const value = true;

...

  .setValue(value.toString())
...

I can say even without supplying a value, it's still false/off.

How do change the state of a switch widget?


Solution

  • Switch.setSelected(boolean)

    setSelected will set the initial state of the switch.