タイトルにもある通りなのですが、ValidationのnotEmptyが作動せず、addしたメッセージも表示されず困っています。勉強中の身でわからないことも多いのでわかりやすく教えていただければ幸いです。
また、save時のifでfalseの際の、処理をmy_layout.ctpで表示させることはできますでしょうか?
作っているものとしては、ブログの記事一覧と同じ画面で記事の作成をできるものを作っています。
ここまで読んでいただきありがとうございました。
PostsTable.php
1<?php 2 3namespace App\Model\Table; 4 5use Cake\ORM\Table; 6use Cake\Validation\Validator; 7 8 9class PostsTable extends Table 10{ 11 public function initialize(array $config) 12 { 13 $this->addBehavior('Timestamp'); 14 } 15 16 public function validationDefault(Validator $validator) 17{ 18 $validator 19 ->notEmpty('title') 20 ->requirePresence('title') 21 ->notEmpty('body') 22 ->requirePresence('body') 23 ->add('body', [ 24 'length' => [ 25 'rule' => ['minLength', 10], 26 'message' => 'body length must be 10+' 27 ] 28 ]); 29 return $validator; 30} 31 32 33}
my_layout.ctp
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <?= $this->Html->charset() ?> 5 <title> 6 <?= $this->fetch('title') ?> 7 </title> 8 <?= $this->Html->css('styles.css') ?> 9</head> 10<body> 11 <?php $this->Flash->render(); ?> 12 <h1>Blog Posts</h1> 13 14 <ul> 15 <?php foreach ($posts as $post) : ?> 16 <li><?= $this->Html->link($post->title,['action'=>'view',$post->id]); ?></li> 17 <?php endforeach; ?> 18 </ul> 19 20 <?= $this->Form->create('null', ['url' => ['action'=>'add']]);?> 21 <?= $this->Form->input('title');?> 22 <?= $this->Form->input('body',['row'=>'3']);?> 23 <?= $this->Form->button('Add');?> 24 <?= $this->Form->end();?> 25 26 27 28 <section class="container"> 29 <?= $this->fetch('content') ?> 30 </section> 31</body> 32</html> 33
PostsController.php
1<?php 2 3// /posts/index 4// /posts 5// /(controller)/(action)/(options) 6 7namespace App\Controller; 8 9class PostsController extends AppController 10{ 11 public function index() 12 { 13 $this->viewBuilder()->layout('my_layout'); 14 $posts = $this->Posts->find('all'); 15 // $this->set('posts', $posts); 16 $this->set(compact('posts')); 17 } 18 19 public function view($id = null) 20 { 21 $post = $this->Posts->get($id); 22 $this->set(compact('post')); 23 } 24 25 public function add() 26 { 27 $this->viewBuilder()->layout('my_layout'); 28 $post = $this->Posts->newEntity(); 29 if ($this->request->is('post')) { 30 $post = $this->Posts->patchEntity($post, $this->request->data); 31 if ($this->Posts->save($post)) { 32 $this->Flash->success('Add New!'); 33 return $this->redirect(['action'=>'index']); 34 } else { 35 $this->Flash->error('Error!'); 36 return $this->redirect(['action'=>'index']); 37 } 38 } 39 $this->set(compact('post')); 40 } 41}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/09/17 10:05
2017/09/17 10:18
退会済みユーザー
2017/09/17 10:39 編集
2017/09/17 10:52
退会済みユーザー
2017/09/17 10:59