Hello, I have two tables:
CREATE TABLE tbl_file
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
type VARCHAR(5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE tbl_article
(
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
language_id INTEGER NOT NULL,
title VARCHAR(128) NOT NULL,
text TEXT NOT NULL,
date_creation DATETIME,
date_update DATETIME,
image_id INTEGER DEFAULT NULL,
pdf_id INTEGER DEFAULT NULL,
CONSTRAINT FK_Article_Language FOREIGN KEY (language_id)
REFERENCES tbl_language (id) ON DELETE CASCADE ON UPDATE RESTRICT
CONSTRAINT FK_Article_Image FOREIGN KEY (image_id)
REFERENCES tbl_file (id) ON DELETE CASCADE ON UPDATE RESTRICT
CONSTRAINT FK_Article_Pdf FOREIGN KEY (pdf_id)
REFERENCES tbl_file (id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
I need to upload an article and maybe one pdf OR image.
The controller is this (not completed):
public function actionCreate()
{
$model=new Article;
$img=new File;
$pdf=new File;
if(isset($_POST['Article']))
{
//print_r($_POST);
if(isset($_POST['File']['img'])){
$rnd = rand(0,9999);
$img->img=$_POST['File']['img'];
$uploadedFile=CUploadedFile::getInstance($img,'img');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$img->name = $fileName;
$img->type = 'img';
echo $img->name;
if($img->save())
{
$uploadedFile->saveAs(Yii::app()->basePath.'/uploaded/'.$fileName);
}
}
//$model->attributes=$_POST['Article'];
/*if($model->save())
$this->redirect(array('view','id'=>$model->id));*/
}
$this->render('create',array('model'=>$model,'img'=>$img,'pdf'=>$pdf));
}
and this is the view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'article-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('enctype' => 'multipart/form-data'),
)); ?>
...
<div class="row">
<?php echo $form->labelEx($model,'image_id'); ?>
<?php echo $form->fileField($img, 'img'); ?>
<?php echo $form->error($img,'img'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pdf_id'); ?>
<?php echo $form->fileField($pdf, 'pdf'); ?>
<?php echo $form->error($pdf,'pdf'); ?>
</div>
...
<?php $this->endWidget(); ?>
I declared on File model class:
public $img;
public $pdf;
public function rules()
{
return array(
array('img', 'file', 'types'=>'jpg, gif, png'),
array('pdf', 'file', 'types'=>'pdf'),
...
);
}
Nothing work and $uploadedFile=CUploadedFile::getInstance($img,‘img’); don’t return nothing.
Someone can help me to resolve? Maybe I used a wrong approach to the problem.