Vienna Vienna - 4 months ago 15
PHP Question

Yii upload a file using a model

I am simply trying to upload a file using a model. I get the exception message in the current situation (see model/controller/view below):

CException
MyFile and its behaviors do not have a method or closure named "save".


If my model extends CActiveRecord instead of CFormModel there is an another Exception:

CDbException
The table "MyFile" for active record class "MyFile" cannot be found in the database.


What is my mistake? These are the files:

MODEL: MyFile.php

class MyFile extends CFormModel {
public $image;
public function rules () {
return array (
array ('image', 'file', 'types' => 'gif, jpg, png'),
);
}
}


CONTROLLER: MyFileController.php

class MyFileController extends CController {
public function actionCreate() {
$model = new MyFile;

if(isset($_POST['MyFile'])) {

$model->attributes=$_POST['MyFile'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save()) {
$path = Yii::app()->runtimePath.'/temp/uploadDirectory/'.$model->image;
$model->image->saveAs($path);
}
}
$this->render('create', array('model'=>$model));
}
}


VIEW: create.php

<h1>File-Upload</h1>

<?php

echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
echo CHtml::activeFileField($model, 'image');
echo CHtml::submitButton('abschicken', array('name' => 'submit'));
echo CHtml::endForm();

?>

Answer

CFormModel doesn't have a method named save(), if you want to call it you have to implement it, but what you want in your case is to use the validate method

And if MyFile doesn't have a related db table then it shouldn't extend CActiveRecord.

You can validate that the uploaded image is a gif, a png or a jpg by calling validate() :

class MyFileController extends CController {
    public function actionCreate() {
        $model = new MyFile;

        if(isset($_POST['MyFile'])) {

            $model->attributes=$_POST['MyFile'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->validate()) {
                //The image is valid, you can save it
                $path = Yii::app()->runtimePath.'/temp/uploadDirectory/'.$model->image;
                $model->image->saveAs($path);
            }
            $this->render('create', array('model'=>$model));
        }
    }
}
Comments