<s-switch> payload bug

The s-switch is not sending the correct payload

<s-switch 
  onchange="this.closest('form')?.requestSubmit();" 
  id="settings[header][settings]_show_discount" 
  name="settings[header][settings][show_discount]" 
  label="Show discount">
</s-switch>

Response
{header: {settings: {show_discount: ["is missing"]}}}

When is turned off, the param is missing.
When is turned on, the param is a string: “on”

Is there a way to send values such as 0/1 or true/false?

Thank you so much as always!

I managed to find a working solution using a hidden field where I’m using the onchange event to update the hidden field first. This sends the correct payload.

Ideally, I would like to use the s-switch directly.

<input 
   type="hidden" 
   value="true" 
   name="settings[header][settings][show_discount]"
   id="setting_header_settings_show_discount">

s-switch (and s-checkbox) follow how the web handles this; you must set a value on the element if you want it to be something other than on when submitted.

Polaris docs: Switch

MDN docs:

1 Like

Thank you very much @Anthony_Frehner for your response.

I tested this and the payload value is still on, am I missing something?

<s-switch name="test" value="true"></s-switch>
<s-switch name="super_test" value="1"></s-switch>

The payload is still ‘on’

Thank you so much for your help as always!

Ok strange, yeah I just confirmed that as well. We have code in that component to handle this, but it doesn’t seem to be working. I’ll dig in.

Thanks for the report!

1 Like

Thanks a lot @Anthony_Frehner!

Updates were just pushed out to the CDN - can you check to see if this was fixed? Thanks.

1 Like

Hey @Anthony_Frehner,

Thank you so much for the update.

I just tested and it looks like the correct value is updated inside the DOM.
It is no longer set to “on” when the s-switch is disabled, however, the param is still not sent to the server when the field is disabled.

I created a sandbox so you can have a look.
https://codesandbox.io/p/sandbox/crazy-yonath-sxl9qg

Thank you so much again for looking into this! :folded_hands:

I understand now that this is not a bug and just the standard way of how HTML works.

I just noticed that the default Rails checkbox <%= form.check_box :notifications %> outputs a hidden field automatically as the standard way of HTML is not to send any value when the input is unchecked.

<input name="notifications" type="hidden" value="0" autocomplete="off">
<input type="checkbox" value="1" name="notifications" id="notifications">

So, this was all needed to make it work

<input name="<%= name %>" type="hidden" value="0" autocomplete="off">
<s-switch
    <% if value %>checked<% end %>
    name="<%= name %>"
    label="<%= label %>">
</s-switch>

Thank you so much @Anthony_Frehner for your fix and your help to figure it out!

1 Like