Auto Login v1.6

A CakePHP Component that will automatically login the Auth session for a duration if the user requested to (saves data to cookies).

Pre-populating form values

Wednesday, March 4th 2009, 1:40am
Topics: Tutorials, CakePHP
Tags: Cakephp, Form, Model, Data
Views: 3,432, Comments: 2

When I first started using CakePHP, I couldn't find a way to pre-populate a form with data. Why would I need this you ask? Well its simple, it would be used to edit something already existent. So what I need to do is grab the data from the database, and then populate the form. Took me a few hours to figure out how to do it, the guide really didn't explain how it should be done (or I just overlooked it). To have the data populate, all you need to do is to set $this->data to the database result. Heres a quick example action:

function edit($id) {
    $user = $this->User->findById($id);
    
    // If data is empty, populate it with user array
    if (empty($this->data)) {
    	$this->data = $user;
    }
    
    // Form is posted
    if ($this->RequestHandler->isPost()) {
   	 	// Do model validation and save
    }
    
    $this->pageTitle = 'Edit User';
}


Pre-populating will only be done if the post/data is empty; so once you post the form, the new data should fill the form. Now that we have given $this->data some value, we need to make sure the form is using the correct model ($this->data['User'] equals form User). In our case it would be the User model and its as easy as that.

// $this->data['User'] will populate here
echo $form->create('User');
echo $form->input('email');
echo $form->input('website');
echo $form->end();
Related Entries:

2 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • KeHoeff
    www.KevinsStory.net
    May 28th 2009, 18:47
    1 hey this is a very interesting article!
  • asdasd
    May 28th, 15:35
    2 Great solution.
    Thanks.