moholh
(Moholh2011)
February 23, 2017, 1:22am
1
Hi there
please help me I 'm getting confused with this problem when I update model with file field if I Don’t upload a file it become empty:
it work perfectly when I upload file but when I don’t want to change existing blob file in the database it become empty!
1.this is my model code
public function rules()
{
return array(
...
array('imgcabinet', 'file', 'allowEmpty'=>true, 'types'=>'jpg,jpeg,gif,png'),
...
);
}
public function beforeSave() {
$file = CUploadedFile::getInstance($this, 'imgcabinet');
if(!empty($file))$this->imgcabinet=file_get_contents($file->tempName);
return parent::beforeSave();
}
this is my controller
$compte=Comptecabinet::model()->findbyPk($id);
$compte->datesession=Yii::app()->user->TimeConnexion;
$compte->save();
thank you in advance
mdomba
(Maurizio Domba Cerin)
February 23, 2017, 7:50am
2
This happens because save() does save all attributes and in the case that you do not upload a new file the file attribute (imgcabinet) is empty (null).
So you need to check if imgcabinet is empty and then save only the rest of parameters, you can use saveAttributes() or save() second parameter for that.
moholh
(Moholh2011)
February 23, 2017, 9:48am
3
I finally solve the problem maybe it’s not a good solution but it work perfectly
this is my new code:
in the model
class Comptecabinet extends CActiveRecord
{
var $file;
.......
public function afterFind()
{
$this->file=$this->imgcabinet;
parent::afterFind();
}
public function beforeSave() {
$file = CUploadedFile::getInstance($this, 'imgcabinet');
if($file!=null && $file->tempName!=null)$this->imgcabinet=file_get_contents($file->tempName);
if(!$this->isNewRecord && $this->imgcabinet==null)$this->imgcabinet=$this->file;
return parent::beforeSave();
}
}
and the controller is the same
$compte=Comptecabinet::model()->findbyPk($id);
$compte->datesession=Yii::app()->user->TimeConnexion;
$compte->save();
this work perfectly thanks for your advice.