oscarotero / form-manager

PHP library to create and validate html forms
MIT License
153 stars 42 forks source link

The attribute "name" is read only! #46

Closed eusonlito closed 9 years ago

eusonlito commented 9 years ago

How can I create a new Input and assign him a name without add function?

Using README example I can't:

//Create an input type="text" element
$name = F::text();

//Use the jQuery syntax to set/get/remove attributes:
$name->attr('name', 'username');
InvalidArgumentException in InputTrait.php line 107:
The attribute "name" is read only!

Thanks.

oscarotero commented 9 years ago

The name attribute cannot be modified because all data structure of the form deppends of it. For example:

//create a form
$form = F::form([
    'username' => F::text(),
    'age' => F::number()
]);

//now we change a name:
$form['username']->attr('name', 'user');

//the html form will be send the data with this structure:
$dataToLoad = [
    'user' => 'lito',
    'age' => 38
];

//and the php form will not load the "user" value because it uses the "username" key
$form->load($dataToLoad);
echo $form['username']->val(); //null

But I can understand that sometimes you want create an individual input without add it to any form. So I've made a change to allow modify the name attribute if the input is not within any form, group or other container:

//we create an input
$input = F::text();

//add a name
$input->attr('name', 'username');

//get the name
echo $input->attr('name'); //username

//add the input to a form
$form = F::form();
$form['user'] = $input;

//Now the name is the key used in the form
echo $input->attr('name'); //returns "user" instead "username"

//And this name cannot be modified
$input->attr('name', 'new-name'); //throws the exception
eusonlito commented 9 years ago

These example was on your README!

I know that I can't modify name attribute, but then, your readme is outdated.

Thanks.

oscarotero commented 9 years ago

Now you can :smile: