Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing Dynamic forms on the Server Side

I've seen a lot of questions around here about implementing dynamic forms in jQuery or other javascript libraries, and I think I managed to get up and running in setting up a dynamic form for my test purposes.

My question is whats the best practice in naming my form fields and processing them on the server side.

I am trying to implement a contact like form where the user can add multiple phone numbers (and types) as well as multiple addresses (and types) something similar to the code below, this is the code block that will be duplicated dynamically.

<div id="phones">
<label>Phone Number</label><input type="text" name="phone1" value="" />
<label>Type</label><input type="text" name="type1" value="" />
</div>

Then I will have a +/- link or button to add another phone or remove a phone. When I submit the form, whats the best way to handle the combo of name/type Should I have the names like indicated above with a postfix of an id like phone1 / type1 or should I use the array naming like phone[] / type[] and match the pairs on the server according to the index.

I am using java (not sure if it makes a difference if it is java or php or whatever) but what would be a best practice of doing this.

Thanks

like image 729
omarello Avatar asked Apr 28 '26 04:04

omarello


1 Answers

Square brackets with indexes seem to be what most frameworks expect, but it does completely depend on your framework. In the Java world, given that there are about a million different frameworks, you have to start from what your framework expects, and adapt your Javascript code appropriately.

The only Java framework I'm familiar enough with to know the answer is Stripes, and it would want square brackets. If your bean had a property

private List<Address> addresses;
public List<Address> getAddresses() { return addresses; }
public void setAddresses(final List<Addresses>) { this.addresses = addresses; }

then the inputs would need names like "addresses[0].street1", "addresses[0].street2", etc. When you add a new block for a new address, you'd have the same fields with "1" instead of "0".

A different Java framework, however, might do things in completely different ways.

like image 123
Pointy Avatar answered Apr 29 '26 19:04

Pointy