Dear all,
I am facing a question regarding the updateAction in my controller.
What I need to do:
When the user click to update , he can choose to update the file or not update the file.
If he chooses to update the file, the server will upload the new file and unlink the old one(php_unlink() ).
If he chooses not to update the file, then the server will not change the old file.
Right now, my code can make this work, however, the name, description and other in my model(database) will not be updated…
That is… only the file can be updated…the name, description…create time…will not change at all!!!
I don’t know what’s wrong with that…
Any ideas?
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (!Yii::app()->user->isGuest && (Yii::app()->user->id == $model->owner_id)||(Yii::app()->user->id =='1'))
{
if(isset($_POST['Apples']))
{
$model->attributes=$_POST['Apples'];
$file=CUploadedFile::getInstance($model,'file');
if (!empty($file)){
$model->file=CUploadedFile::getInstance($model,'file');
}
else{
$model->file=Apples::model()->findByPk($model->id)->path;
}
if($model->save())
{
$fileSavePath = "uploads/".$model->c_id."/".$model->owner_id."/" ;
$filename = preg_replace('/\s+/', '', $model->file);
if(file_exists($fileSavePath.$filename)){
throw new CHttpException(400,'Please do not upload the same file, if it is not, please CHANGE ITS NAME, refresh this page and re-upload it. Thank you! ');
}
if (!file_exists ($fileSavePath)){
mkdir ($fileSavePath, 0777, true);
}
$path='http://www.xxxxxx.com/uploads/'.$model->c_id.'/'.$model->owner_id.'/'.$filename;
$pathold='uploads/'.$model->c_id.'/'.$model->owner_id.'/';
if (file_exists ($pathold.$model->filename)){
unlink($pathold.$model->filename);
}
$model->file->saveAs("uploads/".$model->c_id."/".$model->owner_id."/".$filename);
$model ->path = $path;
$model ->filename =$filename;
$model ->save();
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
else {
throw new CHttpException(403,"Only owner can do the update action.");
}
}
Thanks!!!