CakePHP3にて、以下のようなコードを書きました。
lang
1// Template 2echo $this->Form->control('image', [ 3 'type' => 'file', 4 'label' => '', 5 'required' => false 6]); 7 8// Model (Table) 9// 画像のアップロード機能は Upload Plugin 3.0 で実装しています 10$validator 11 ->notEmpty('image', __('必須'), 'create') 12 ->add('image', [ 13 'uploadedFile' => [ 14 'rule' => ['uploadedFile', ['types' => ['image/jpeg', 'image/png', 'image/gif']]], 15 'last' => true, 16 'message' => __('gif, jpeg, png のみ可') 17 ] 18 ]); 19 20return $validator; 21 22// Controller 23public function add() 24{ 25 $post = $this->Posts->newEntity(); 26 if ($this->request->is('post')) { 27 $post = $this->Posts->patchEntity($post, $this->request->getData()); 28 29 $post->user_id = $this->Auth->user('id'); 30 31 if ($this->Posts->save($post)) { 32 $this->Flash->success(__('成功')); 33 return $this->redirect(['action' => 'index']); 34 } else { 35 $this->Flash->error(__('失敗')); 36 } 37 } 38 $this->set(compact('post')); 39 $this->set('_serialize', ['post']); 40}
この状態で、ファイルを選択せずにPOSTすると"Field 'image' doesn't have a default value"というエラーが出てきてしまいます(デフォルト値を設定していなからこそ、notEmpty()で空のフィールドを弾きたいのですが……)。
そして、
lang
1$validator->notEmpty('image', __('必須'), 'create')
を
lang
1$validator->notEmpty('image', __('必須')) 2// または 3$validator->notEmpty('image', __('必須'), false)
に変更すると、なぜかバリデーションが機能します(ファイルを選択せずにPOSTすると「必須」と表示されます)。
また、他のフィールドに対するバリデーションでは、第3引数に'create'を指定した場合であっても、上記のような問題は発生していません。
原因がお分かりになる方がいらっしゃいましたら、ご回答のほど、よろしくお願いいたします。
あなたの回答
tips
プレビュー