コントローラーにメソッドを追加
<?php // /posts/index // /posts // /(controller)/(action)/(options) namespace App\Controller; class PostsController extends AppController { public function index() { $posts = $this->Posts->find('all'); // ->order(['title' => 'DESC']) // ->limit(2) // ->where(['title like' => '%3']); $this->set('posts', $posts); } public function view($id = null) { $post = $this->Posts->get($id); $this->set(compact('post')); } }
src->template->view.ctp
<?php $this->assign('title', 'Blog Detail'); ?> <h1> <?= $this->Html->link('Back', ['action'=>'index'], ['class'=>['pull-right', 'fs12']]); ?> <?= h($post->title); ?> </h1> <p><?= nl2br(h($post->body)); ?></p>
Postの追加: NewEntity
<h1> <?= $this->Html->link('Add New', ['action'=>'add'], ['class'=>['pull-right', 'fs12']]); ?> Blog Posts </h1>
public function add() { $post = $this->Posts->newEntity(); $this->set(compact('post')); }
Cakeのformヘルパー: src->template->view.ctp
<?= this->Form->create($post); ?> <?= this->Form->input('title'); ?> <?= this->Form->input('body', ['row'=>'3']); ?> <?= this->Form->button('Add'); ?> <?= this->Form->end(); ?>
データの入力
if ($this->request->is('post')){ $post = $this->Posts->patchEntity($post, $this->request->data); $this->Posts->save($post); return $this->redirect(['action'=>'index']); }
validation:PostsTable.php
<?php namespace App\Model\Table; use Cake\ORM\Table; use Cake\Validation\Validator; class PostsTable extends Table { public function initialize(array $config) { $this->addBehavior('Timestamp'); } public function validationDefault(Validator $validator) { $validator ->notEmpty('title') ->requirePresence('title') ->notEmpty('body') ->requirePresence('body') ->add('body', [ 'length' => [ 'rule' => ['minLength', 10], 'message' => 'body length must be 10+' ] ]); return $validator; } }
PostsController
public function add() { $post = $this->Posts->newEntity(); if ($this->request->is('post')) { $post = $this->Posts->patchEntity($post, $this->request->data); if($this->Posts->save($post)){ return $this->redirect(['action'=>'index']); } else { } } $this->set(compact('post')); } }