There is a news editing page. I update the record in this way:

$model=News::model()->findByPk($_GET['id']); if(isset($_POST['News'])) { $model->attributes=$_POST['News']; $model->save(); } 

All is good, only I have a field that contains an image. If I leave an empty file selection form, then the value of this field will overwrite with an empty string. How can I prevent the update of this field if I do not select the file, those leave the old image?

  • The rules model has a string of type array('img', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'), ,? That is, resolves the unloaded photos during the update - Alexey Shimansky
  • 'allowEmpty' => true is written, if without this line, if there is no image, it says: "It is necessary to fill in the“ Image ”field.”, as if it is mandatory. With 'allowEmpty' => true it turns out to send the form, but the old image overwrites the void - Jeque
  • $model = $this->loadModel($id); $old_img = $model->img; $model->img = ''; if(isset($_POST['News'])) { $model->attributes = $_POST['News']; if(empty($model->img)) $model->img = $old_img; $model->save(); } $model = $this->loadModel($id); $old_img = $model->img; $model->img = ''; if(isset($_POST['News'])) { $model->attributes = $_POST['News']; if(empty($model->img)) $model->img = $old_img; $model->save(); } try it like this - Alexey Shimansky
  • It can be so, but this method is more like a crutch - Jeque
  • Okay, then if(isset($_POST['News'])) { if ($_POST['News']['image']=='') unset($_POST['News']['image']); $model->attributes=$_POST['News']; if($model->save()) {...............} } if(isset($_POST['News'])) { if ($_POST['News']['image']=='') unset($_POST['News']['image']); $model->attributes=$_POST['News']; if($model->save()) {...............} } if(isset($_POST['News'])) { if ($_POST['News']['image']=='') unset($_POST['News']['image']); $model->attributes=$_POST['News']; if($model->save()) {...............} } - Alexey Shimansky

1 answer 1

Solved the problem by specifying which attributes to save if no image is selected. So actually the code looks like:

  if(isset($_POST['News'])) { $model->attributes=$_POST['News']; // Если выбрано изображение. if (!empty($_FILES['News']['name']['image'])) { // Загружаем новое изображение. $model->image=CUploadedFile::getInstance($model,'image'); $path=Yii::getPathOfAlias('webroot').'/upload/'.$model->image->getName(); $model->image->saveAs($path); // Обновляем запись $model->save(); } else { // Обновляем запись без изображения. $model->save(true, array('title', 'desc', 'body', 'alias', 'status')); } }