When you create a form element with CakePHP like so:
echo $this->Form->input('User.first_name');
You start with a blank field. When you put in your name John
and submit the form, if the form does not validate, the name John
is still there when you return to the page to fix your validation errors. This is convenient because you can fix your mistakes without having to retype the parts you got right.
How does it get put back as the value?
I need to know this because once the form is submitted successfully and you leave the page and come back the form is blank again.
I am saving the name as a session so I can do this instead:
$first_name = $this->Se开发者_Python百科ssion->read('Cart.User.first_name');
echo $this->Form->input('User.first_name',array('value'=>$first_name));
Now if you lave the page and come back, the name will still be there but that breaks the original logic preventing it from putting what you type back in when the form fails to validate.
Let me give you an example.
I am creating my name element like:
$first_name = $this->Session->read('Cart.User.first_name');
echo $this->Form->input('User.first_name',array('value'=>$first_name));
I fill out the form correctly and am taken to a final checkout page. I see that I misspelled my name as Jhon
. So I clicked the edit button and am taken back to the form, since I manually set the value
in my form my data is all still there. I correctly retype my name as John
and submit the form. For some other reason the form did not validate and I am taken back to the form, but instead of displaying John
like it originally would, it now displays Jhon
again because when I manually set value
I am overriding the default with whatever is still in the session.
So if I know how CakePHP puts the data back in the form when it does not validate, I can put the session data back in the same way without overriding the default.
The data is passed back to the form in a POST data call. The FormHelper auto-magic elements use that data to populate the value attributes of the fields. If you leave the page, the post information doesn't get passed along.
You will need to save $this-data block in a session value to keep it while moving from page to page.
精彩评论