DBにデータがある場合にカラムを更新しない
前提
ユーザーページで”コメント”と”ユーザー画像”を編集が可能になっている
やりたいこと
DBに画像ファイルが保存されていて空のまま更新ボタンを押した時に空の値を更新するのではなく、そのまま画像を表示させたい。
方法①
現在DBに入っているデータを取得して更新する。
UsersController.php
if ($this->request->is('post') || $this->request->is('put')) {
$img = $this->request->data['User']['image_name']['tmp_name'];//一時保存パス
$image_name = $this->request->data['User']['image_name']['name'];//ファイル名
if ($image_name) { //ファイルが選択されていればimgディレクトリに移動
$this->request->data['User']['image_name'] = $image_name;
move_uploaded_file($img, '../webroot/img/' . $image_name);
} else {//ファイルが選択されなければテーブルデータのファイル名取得
//該当するidのimage_nameカラムの値を取得
$image_name = $this->User->find('first', array('conditions' => array('id' => $id), 'fields' => 'image_name'));
$this->request->data['User']['image_name'] = $image_name['User']['image_name'];
}
if ($this->User->save($this->request->data)) {//postされたデータをデータテーブルに保存
$this->Flash->success(__('ユーザー情報を編集しました'));
return $this->redirect(array('action' => 'view', $id));
}
$this->Flash->error(__('ユーザーを登録できませんでした。やり直してください。'));
} else {
$this->request->data = $this->User->findById($id);
unset($this->request->data['User']['password']);
}
方法②
ファイルが選択されていない場合はimage_nameカラムを更新しない
UsersController.php
if ($this->request->is('post') || $this->request->is('put')) {//postもしくはputのリクエストが行われた場合
$img = $this->request->data['User']['image_name']['tmp_name'];//image_name配列の一時保存パスを代入
$image_name = $this->request->data['User']['image_name']['name'];//image_name配列のファイル名を代入
if ($image_name) {//ファイルが選択されていればimgディレクトリに移動
$this->request->data['User']['image_name'] = $image_name;//DBに保存するファイル名
move_uploaded_file($img, '../webroot/img/' . $image_name);//imgディレクトリにファイルを保存
$this->User->save($this->request->data);//リクエストされたデータを保存
$this->Flash->success(__('ユーザー情報を編集しました'));
return $this->redirect(array('action' => 'view', $id));
} else {//ファイルが選択されていない場合
$this->User->save($this->request->data, false, array('comment', 'id'));//コメントとIDを保存
$this->Flash->success(__('ユーザー情報を編集しました'));
return $this->redirect(array('action' => 'view', $id));
}
$this->Flash->error(__('ユーザーを登録できませんでした。やり直してください。'));
} else {
$this->request->data = $this->User->findById($id);
unset($this->request->data['User']['password']);
}
下記同じ処理を2回行なっているため一回で行う方法はないか?
$this->Flash->success(__('ユーザー情報を編集しました'));
return $this->redirect(array('action' => 'view', $id));