Formation v2.2

Formation is a lightweight class that can build all necesssary elements for a form, process the posted data (post, get, request), validate the data based on a schema and finally return a cleaned result.

Recent Thoughts

Pre-populating form values

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

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:

1 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]