Switches with non-unique field names returning string values instead of arrays

104 Views Asked by At

I created a series of switches in my Gmail add-on.
After clicking a button, I want to access the values of the switches. Some of the switches can have the same field names, which I'm setting using Switch::setFieldName function, like so:

var switchKeyValue = CardService.newKeyValue()
    .setSwitch(CardService.newSwitch()
        .setFieldName(email)
        .setValue(name));

Later on, I am iterating over the input values (values of the switches) of the sent form using:

// "e" is the event object passed to the event listener
var form = e.formInput;
var emails = [];
for (key in form) {
    if (form.hasOwnProperty(key)) {
        emails.push(key);
    }
}

Normally, you would expect that the fields with the same name would have their values overwritten as they would be added in the formInput object.
For example, if I added 3 switches with the field name "car" and values (in this order) "red", "blue", "green", the resulting form would include only {"car": "green"}.

However, the documentation for the setFieldName function says:
"Unlike other form fields, this field name does not need to be unique. The form input values for switches using the same field name are returned as an array. The array consists of the values for all enabled switches with that field name."

So one would expect to receive something like {"car": ["red", "blue", "green"]} instead.
Yet, I am only getting string values for each of the switch, never an array containing multiple strings.

As a workaround I set the field name to contain both the original field name and the value of the field using a concatenation of the strings (and a split character), so that I get a set of ALL the widget values. However, this is not ideal, since I have to later split the string to parse out the key and the value of the field. Besides, it might not even work if the split character is a part of the original field name.

Basically, I want to collect all the switch values of the form, but need to keep track of the ones that are related (those having the same field name).
What is the best way to achieve this?

0

There are 0 best solutions below