Pregunta

I have a table-based form with which I intend to enter data into my application. Each <tr> is dynamically added through Javascript for every item I want to add. However, I cannot figure out how to manage posting the data. For example, I have this:

<tr>
  <td><input type="text" name="name1"></td>
  <td><input type="text" name="value1"></td>
</tr>
<tr>
  <td><input type="text" name="name2"></td>
  <td><input type="text" name="value2"></td>
</tr>

The params I get are:

{ "name1" => "derp", "value1" => "herp", "name2" => "Edward James Olmos", "value2" => "Boss voice"}

How would I parse that into DataMapper objects?

¿Fue útil?

Solución

It's better to use 'arrayed' names here, so that all dynamically added fields get passed as one collection. There are two ways to approach it with array names, either you do the numbering yourself:

<tr>
  <td><input type="text" name="array_of_names[2]"></td>
  <td><input type="text" name="array_of_values[2]"></td>
</tr>

(and keep track of the now-to-be-added number as a global variable in your javascript) See the params structure you'll get then -- will be a lot easier to manage and connect on the server side.

Or leave out the numbering and use this:

<tr>
  <td><input type="text" name="array_of_names[]"></td>
  <td><input type="text" name="array_of_values[]"></td>
</tr>

While easier to code on the frontend side, it will be a bit harder to connect names with values on the server side (passed params hash won't have numerical keys).

Relevant js code is easy to find by googling "javascript add form fields". Here's an example with numbered field names: http://www.randomsnippets.com/2008/02/21/how-to-dynamically-add-form-elements-via-javascript/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top