Using CakePHP to auto-populate forms is a great way to save your time when developing your applications. Here is an example of some code that isn’t going to auto-populate the form in my view file.
public function edit() { if ( !empty($this->data) ) { $this->User->save($this->data); $this->User->Profile->save($this->data); //... flash and redirect ... } else { $profile = $this->Session->read("User"); $this->set("profile", $profile); } }
Just one line will allow the edit.ctp (the view corresponding to the edit action in my controller) form be to auto-populated! Let me share it with you.
Simply add $this->data = $profile; right after the $profile variable is defined.
The $form helper looks in the controller’s $this->data to populate the form in edit.ctp. In your own code, all you have to do is set $this->data to equal to the data you want to auto-populate. It could be a database result or a static array. It’s up to you.
It’s really quite simple when you think about it. It would have been so agonizing to have to fill everything in manually.
Happy baking.
Thank you, it works! And better still, it’s so simple.
Hi Ryan!
Thanks again for good advice, you have helped me a lot! :)