cakephp(2.7.8)
PHP 5.6
MySQL 5.6
以下の投稿と同じ内容のようです。
バリデーションのallowEmptyが動かない
ユーザーのプロフィールページを作ってます。
「名前」と「画像」のみのシンプルなページです。
それぞれバリデーションを用意したのですが、
画像は、必須入力ではないため、入力時のみチェックしたいです。
allowEmpty = true
としたにも関わらず、「画像ではありません。」と表示されてしまいます。
どうすれば、画像未入力時はスルー出来るようになるでしょうか?
MyPagesController.php
php
1 public function edit() 2 { 3 //使うモデルをロードする 4 $this->loadModel("User"); 5 6 7 8 //POSTされた(編集された)場合の処理 9 if($this->request->data) 10 { 11 12 13 14 //画像の編集あり 15 $image = $this->request->data['Post']['image']; 16 if($image !== null) 17 { 18 $this->request->data['User']['image'] = $image; 19 } 20 21 $this->request->data['User']['id'] = $this->Session->read('user_id'); 22 $this->User->set($this->request->data); 23 24 25 //バリデーションの用意 26 $this->User->validate = array( 27 'name' => array( 28 array( 29 //'rule' => 'notEmpty', 30 'rule' => 'notBlank', 31 'message' => 'お名前を入力してください' 32 ), 33 array( 34 'rule' => array('isUniqueName', $this->Session->read('user_id')), 35 'message' => 'こちらのお名前は、すでに使用されています' 36 ) 37 ) 38 , 39 'image' =>array( 40 'rule1' => array( 41 //拡張子の指定 42 'rule' => array('extension',array('jpg','jpeg','gif','png')), 43 'message' => '画像ではありません。', 44 'allowEmpty' => true, 45 ), 46 'rule2' => array( 47 //画像サイズの制限 48 'rule' => array('fileSize', '<=', '500000'), 49 'message' => '画像サイズは500KB以下でお願いします', 50 ) 51 ) 52 ); 53 54 55 56 //バリデーションエラーがあれば編集画面を再表示 57 if(!$this->User->validates()) 58 { 59 $this->set('title', 'プロフィール編集'); 60 $this->render('edit'); 61 } 62 else 63 { 64 65 if($image !== null) 66 { 67 //バリデーションが終わったので、ファイル名だけセットし直す 68 $this->request->data['User']['image'] = $this->_copyImage($image); 69 $this->User->set($this->request->data); 70 } 71 72 73 74 //会員情報を更新 75 if($this->User->save()) 76 { 77 $this->redirect('/Mypages/'); 78 } 79 80 81 } 82 83 } 84 //初期表示時 85 else 86 { 87 //セッションから会員IDを取得 88 $user_id = $this->Session->read('user_id'); 89 90 //会員情報を取得 91 $user = $this->User->findById($user_id); 92 93 $this->request->data['User'] = $user['User']; 94 95 $this->set('title', 'プロフィール編集'); 96 } 97 98 99 100 101 102 }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。