I’ve run through the cookbook tutorial How to upload a file using a model as well as read many forum posts, but I still cant get this to work with my own code.
-
I thought the whole idea about CActiveRecord was to handle data to and from database. Therefore it’s very confusing when this tutorial uses a model of this type. Is there an easy explanation for this?
-
OK, I try to integrate the example with my own models and code. I have a model class (for my db table) that extends CActiveRecord and it looks like this:
class quiz_3dqs_questions extends CActiveRecord {
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'quiz_3dqs_questions';
}
public function rules() {
return array(
array('question, answer', 'required'),
);
}
public function attributeLabels() {
return array(
'question_id' => 'Question Id',
'gruop_id' => 'Group id',
'question' => 'Question',
'has_image' => 'Has image',
'answer' => 'Answer',
'created_date' => 'Created date',
);
}
}
I don’t want to store my uploaded images in the db itself, but on disk. There for I cant understand why I should mess with my file upload in this class, but I try to do it since thats what the tutorial says, so I add this to the class:
-
public $image; // put it on top
-
array(‘image’, ‘file’, ‘types’=>‘jpg’), // put it inside the rules function
My controller for this model looks like this: (I’m only pasting the relevant function)
public function actionEdit() {
if(isset($_POST['quiz_3dqs_questions'])) {
$tmp_model=quiz_3dqs_questions::model()->findbyPk($_POST['quiz_3dqs_questions']['question_id']);
$tmp_model->attributes=$_POST['quiz_3dqs_questions'];
$tmp_model->image=CUploadedFile::getInstance($tmp_model,'image');
if ($tmp_model->validate()) { $tmp_model->save(); }
$tmp_model->image->saveAs('/images/quiz_3dqs/test');
}//if
...
My html input form has this:
<?php echo CHtml::activeFileField($question,"image"); ?>
Problem is that when uploading a file i get the error:
Fatal error: Call to a member function saveAs() on a non-object in /.../protected/controllers/Quiz_3dqsController.php on line 56
The $_FILES array do contain the file, I just cant get it working with the "Yii way"
A var_dump of $tmp_model->image right after it’s called the getInstance function returns NULL.
Any ideas where I might have gone wrong? …I’m 5 minuttes from starting to parse the $_FILES array…