csandreas1
csandreas1

Reputation: 2388

Coldfusion ignores posted html array fields

I am posting an html form which multiple input names look like that: left_impedance_TYMP[]

However when accessing them in coldfusion, it ignores empty fields.

FORM["left_impedance_TYMP[]"]

Inspecting POST request seems correct.

Is there a solution on this?

Upvotes: 0

Views: 95

Answers (1)

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

When you have multiple form fields of the same name, with or without brackets, both a GET and a POST ignore empty fields values.

Form:

<form action="brackets_process.cfm" method="GET">
    <input type="text" name="foo" value="A"><br>
    <input type="text" name="foo" value="B"><br>
    <input type="text" name="foo" value="C"><br>
    <input type="text" name="foo" value="D"><br>
    <button>Submit</button>
</form>

Processing:

<cfdump var="#url#" label="URL">
<p></p>
<cfdump var="#form#" label="FORM">

A GET querystring brackets_process.cfm?foo=A&foo=B&foo=C&foo=D

A POST brackets_process.cfm

If you add brackets to foo[], the querystring is encoded and the struct key contains the brackets.

brackets_process.cfm?foo%5B%5D=A&foo%5B%5D=B&foo%5B%5D=C&foo%5B%5D=D

A POST is still a list of submitted values.

Converting POST data to an array.

PHP automatically converts field names that end with a bracket to an array. ColdFusion has an application.cfc setting this.sameformfieldsasarray=true; that @Alex linked. Problem is that its a global setting and could change a considerable amount of existing functionality.

With that setting on, a POST converts the values to an array.

A GET sticks to a list. So if you leave out a value (B), the value of url["foo[]'] is a list with 4 elements, where the 2nd element is empty.

Leaving a value (B) out of a POST, however, returns an array with 4 elements, where the 2nd value is empty.

So you need to determine if you want to make a global change that affects all current functionality or if you can add some conditional logic that checks the number of elements in a list vs. the expected number of fields.

I've written code in the past that named fields something like name="fieldName.#counterValue#", then parsed the field names to set positional values in a list or array to account for empty values.

Upvotes: 4

Related Questions