I am modifying a form component that is part of a web application to support users adding and removing extra form fields during run time.
The data from the form is setted to a php object when the form is submitted:
<?php
class users {
public function setName($name){
(...)
}
public function getName(){
(...)
}
public function setSomeAttribute($name){
(...)
}
public function getSomeAttribute(){
(...)
}
}
The form is generated like so:
$form = new Form();
$form->addField('Text', 'Name', (... some other parameters...))
->addField('Address', 'SomeAttribute', (... some other parameters...));
A view is generated containing a tree of objects representing each field (some “fields” such as addresses can contain child fields such as text inputs.
Given that we know the name of the object property, the form component can then easily bind the result of that form field to the respective object property using getters and setters.
The issue I am facing now is this: I need to allow the user to add fields during run time. This will work using Jquery and also fallback for users without javascript.
Assuming we have a page where the user can edit his profile and add multiple shipping addresses. He will have a button that says “add address”. Clicking this button would doe the following:
- For users with javascript enabled, the user will immediately see a new “address field” which consists of a few dropdowns and text fields added.
- For users without javascript enabled, the page will refresh, and the new “address field” which consists of a few dropdowns and text fields added.
What is the best way to let the PHP side know that these new fields exist and we need to get the posted data from them?
all form elements will be submitted in the request and available to PHP. so you just need to refer to the elements using whatever name the elements were assigned in the form.
for the country for 2 addresses you’d want to name elements like “addr_1_country”, “addr_2_country”, or alternately “addr_country[]” for both to make the values available in an array. if you use the former, you could loop thru the names “addr_$i_country” until you find them unset (or get JQuery to update a count value that also gets submitted, like “addr_count” that tells you how long to loop).
either way you just need to know the names. but if you can only specify “Addresses” and/or the child fields are given names that you cannot assign yourself then you might have a problem. maybe your “->addField()” is smart enough to name the them for you. otherwise update “Form” to name automatically or accept ‘name’ args.