Fields with * are mandatory

Dios - Do It Open Source
 

Upload file using model


To upload a file using a form model you need:


A model:

class UploadForm extends CFormModel
{
	public $destinationFolder;
	public $myfile;

	public function rules()
	{
		return array(
			array('destinationFolder', 'required'),
			array('myfile', 'file', 'allowEmpty'=>false, 'types'=>'zip, tar.gz', 'maxSize'=>2097152),
		);
	}

	public function attributeLabels()
	{
		return array(
			'destinationFolder'=>Yii::t('upload', 'Target'),
			'myfile'=>Yii::t('upload', 'Select file'),
		);
	}
}

Pay attention to next:
1. Don't add file input to 'required', but use 'allowEmpty'=>false to validate it, else you will receive always an error that your input cannot be blank, even when file input is set.
ex. array('myfile', 'file', 'allowEmpty'=>false, 'types'=>'zip, tar.gz', 'maxSize'=>2097152),
2. All rules for file input must be in same rule raw, else, when the file input value isn't set, will throw an error for each rule you set.


A controller

class UploadController extends CController
{
    public function actionCreate()
    {
        $model=new Upload;
        if(isset($_POST['upload']))
        {
            $model->attributes=$_POST['upload'];
            $model->myfile=CUploadedFile::getInstance($model,'myfile);
            $pathToSave = $model->destinationFolder.'/'.$model->myfile->name;
            $model->myfile->saveAs($pathToSave);
        }

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

    }
}


A view

<?php
echo "\n".'<div class="form">';
 $form=$this->beginWidget('CActiveForm', array(
 'id'=>'upload-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
 ));

 echo $form->errorSummary($model);

 echo "\n".'<div class="row">';
 echo "\n".$form->labelEx($model, 'destinationFolder');
 echo "\n".$form->dropDownList($model, 'destinationFolder', array(
 'one'=>'one',
 'two'=>'two'
 ));
 echo "\n".'</div>';

 echo "\n".'<div class="row">';
 echo "\n". $form->labelEx($model, 'myfile');
 echo "\n". $form->fileField($model, 'myfile');
 echo "\n".'</div>';

 echo "\n".'<div class="row buttons">';
 echo "\n".CHtml::submitButton('Submit', '', array());
 echo "\n".'</div>';

 $this->endWidget();

echo "\n".'</div>';
	
?>

Pay attention to:
Because using a file input, you need to declare that the form will use enctype to be multipart/form-data
ex: 'htmlOptions'=>array('enctype'=>'multipart/form-data')

Other information:
1. You will must check on server side if the mime of file it is what is supposed to be.

2. Check if destinationFolder is correct and isn't changed by user on client side.