bigskysoftware / htmx-extensions

103 stars 30 forks source link

WS json encoding of form with array data not correctly encoding as array with single item #35

Open PhilipBatten opened 4 weeks ago

PhilipBatten commented 4 weeks ago

I am using the WS extension to post a dynamic form where items can be added and removed. The key of the input is something like items[] to allow the multiple items to be submitted as an array. When there are 2 or more inputs with the name in the form the message posted is correct:

{"name":"multiple array item","items[]":["a","b"],"HEADERS":{"HX-Request":"true","HX-Trigger":null,"HX-Trigger-Name":null,"HX-Target":null,"HX-Current-URL":"http://localhost:8080/"}}

But when only a single item exists this is the message: {"name":"single array item","items[]":"a","HEADERS":{"HX-Request":"true","HX-Trigger":null,"HX-Trigger-Name":null,"HX-Target":null,"HX-Current-URL":"http://localhost:8080/"}}

As you can see the items[] value is only a string not an array for the single item. When posting the form in the traditional way the post data is always an array.

I think this is a result of line 342 (in the main branch) on ws.js: var rawParameters = Object.assign({}, results.values)

An additional check needs to be added after this to convert any string values to arrays where the key ends in []

I have a test repository here where I implemented a naive fix: https://github.com/PhilipBatten/htmx-ws-bug

I will attempt an PR to fix this issue if there is no objection.

Thanks.