Mostly as a personal practice, i’m writing a framework for a personal website i’m working on. Currently I’m trying to create a generic way to display forms on my website. I’m using JSON models to model the form, which is transformed into HTML by PHP. What i’m currently trying to allow is something like this:
[type] [contact address]
[type] [contact address]
+ Add More
I know that with form element names like “type[]”, the value of the various type fields is sent as an array to php. However, in this case, a type and a contact address belong together. I know various ways to achieve this, like looping over the types, and then getting the related other fields, but somehow transforming it into an associative array seems much easier to use in the code.
Note, i know various ways to achieve this, but i’m trying to go for some best practices. I’d prefer doing this in PHP, as i’m trying to minimize the amount of javascript on my website.
You can actually build multidimensional arrays like
contact[id][type]andcontact[id][address]. Therefore, if you have anid, which could be an incremental value if you are adding new ones, supply the sameidfor both. PHP will see it as a multidimensional array like$_POST['contact'][1]['type'] == 'sometype, $_POST['contact'][1]['address'] == 'theaddress'.So your new form inputs look like:
You can then loop over
$_POST['contact']:And the
var_dump($_POST)with sample input would look something like:The method you use to generate the ids in JavaScript (assuming you don’t know them ahead of time) is entirely up to you. You could just start a variable at
1and increment it each time you click theadd morelink. The value ofiddoesn’t really matter, as long as it is the same for the pair of inputs.