10.1.9 記事の追加

The original text for this section has changed since it was translated. Please help resolve this difference. You can:

More information about translations

データベースを読み、記事を表示できるようになりました。今度は、新しい投稿ができるようにしてみましょう。

まず、PostsControllerの中に、add()アクションを作ります。

<?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. ?>

add()アクションの動作は次のとおりです。もし、送信されたフォームのデータがemptyでないなら、Postモデルを使ってデータの保存を試みます。何らかの理由で保存できなかった場合には、単にビューを表示します。この時に、ユーザバリデーションエラーやその他の警告が表示されることになります。

ユーザがフォームを使ってデータをPOSTした場合、その情報は、$this->dataの中に入ってきます。pr()を使うと、内容を画面に表示させて、確認することができます。

$this->flash()関数は、(flashレイアウトを使用して)ユーザに1秒間メッセージを表示(flash)してから、他のURL(この場合には/posts)にユーザを移動させる、コントローラのメソッドです。もし、DEBUGが0に設定されている場合、$this->flash()は自動的にリダイレクトします。しかし、DEBUG > 0の場合には、flashレイアウトが表示され、そのメッセージをクリックすることで、リダイレクトされる動作になります。

save()メソッドを呼ぶと、バリデーションエラーがチェックされ、もしエラーがある場合には保存動作を中止します。これらのエラーがどのように扱われるのかは次のセクションで見てみましょう。