Upload Different Files And Save In Same Db Tbl

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.

Hi gdang,

try to show the variable $_FILES with something like:




if(isset($_POST['Article']))

{

   if(isset($_POST['File']['img']))

   {

      print_r($_FILES);

      return;

      .......

   }

   .....

}



and checks if it contains the infos about the uploaded file.

Yes, There are correct informations, maybe Ill’no use YII classes and I’ll manage them by myself

I tried your code in my local project and


CUploadedFile::getInstance($img,'img');

return a correct object, it’s strange that you have NULL.

Could you post the value of $_POST and $_FILES?

Resolved:

Model:


class Upload extends CFormModel

{

	public $img;

	public $pdf;

	

	public function rules()

	{

		return array(

			array('img', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),

			array('pdf', 'file', 'types'=>'pdf', 'allowEmpty'=>true),

		);

	}

}

Controller:


	public function actionCreate()

	{

		$model=new Article;

		$upload=new Upload;


		if(isset($_POST['Article']) && isset($_POST['Upload']))

		{

			$model->attributes=$_POST['Article'];

			$upload->attributes=$_POST['Upload'];

			if($model->validate()  && $upload->validate()) //valido l'upload per non inserire files di tipo errato

			{

				$model->image_id = $this->saveFile($upload, 'img');

				$model->pdf_id = $this->saveFile($upload, 'pdf');

				$model->save();

				$this->redirect(array('view','id'=>$model->id));

			}	

		}

		$this->render('create',array('model'=>$model,'upload'=>$upload));

	}

	

	private function saveFile($model, $type)

	{

		$dir = Yii::getPathOfAlias('application.uploaded'); //salvo in protected/uploaded

		$file=CUploadedFile::getInstance($model,$type);	//il nome del tipo è lo stesso nel tipo nel Model.Upload e type di Model.File.type

		if($file){

			$fileDb= new File; // id name type

		

			$fileName = uniqid()."-".$file->getName(); //id unico

			$file->saveAs($dir.'/'.$fileName);

			

			$fileDb->name=$fileName;

			$fileDb->type=$type;

			if($fileDb->save())

				return Yii::app()->db->getLastInsertID();

		}

		return null;

	}

View:


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'article-form',

	'enableAjaxValidation'=>false,

	'htmlOptions'=>array('enctype' => 'multipart/form-data'), // !!!

)); ?>


...


	<div class="row">

		<?php echo CHtml::error($upload, 'img')?>

		<?php echo CHtml::activeFileField($upload, 'img')?>

	</div>

	

	<div class="row">

		<?php echo CHtml::error($upload, 'pdf')?>

		<?php echo CHtml::activeFileField($upload, 'pdf')?>

	</div>


...


<?php $this->endWidget(); ?>