10.1.9 Adding Posts

Reading from the database and showing us the posts is a great start, but lets allow for the adding of new posts.

First, start by creating an add() action in the PostsController:

<?php
class PostsController extends AppController {
	var $name = 'Posts';

	function index() {
		$this->set('posts', $this->Post->find('all'));
	}

	function view($id) {
		$this->Post->id = $id;
		$this->set('post', $this->Post->read());

	}

	function add() {
		if (!empty($this->data)) {
			if ($this->Post->save($this->data)) {
				$this->flash('Your post has been saved.', '/posts');
			}
		}
	}
}
?>
  1. <?php
  2. class PostsController extends AppController {
  3. var $name = 'Posts';
  4. function index() {
  5. $this->set('posts', $this->Post->find('all'));
  6. }
  7. function view($id) {
  8. $this->Post->id = $id;
  9. $this->set('post', $this->Post->read());
  10. }
  11. function add() {
  12. if (!empty($this->data)) {
  13. if ($this->Post->save($this->data)) {
  14. $this->flash('Your post has been saved.', '/posts');
  15. }
  16. }
  17. }
  18. }
  19. ?>

Here's what the add() action does: if the submitted form data isn't empty, try to save the data using the Post model. If for some reason it doesn't save, just render the view. This gives us a chance to show the user validation errors or other warnings.

When a user uses a form to POST data to your application, that information is available in $this->data. You can use the pr() to print it out if you want to see what it looks like.

The $this->flash() function called is a controller method that flashes a message to the user for a second (using the flash layout) then forwards the user on to another URL (/posts, in this case).

If DEBUG is set to 0, $this->flash() will redirect automatically. If DEBUG is greater than 0 (DEBUG is 2 by default) flash messages do not redirect.

Calling the save() method will check for validation errors and abort the save if any occur. We'll discuss how those errors are handled in the following sections.