CHtml FileField

Using CHtml class we are creating fileField in yii framework. This post will help you to understand about how to upload file in different method, how to get and save the uploaded file in controller, file validation in model yii framework.

DONT FORGET multipart/form-data

<?php $form=$this->beginWidget('CActiveForm', array(
 'htmlOptions'=>array('enctype' => 'multipart/form-data'),
)); ?>


public static string activeFileField(CModel $model, 
                                string $attribute, 
                                array $htmlOptions=array ( ))
public static string fileField(string $name, 
                                string $value='', 
                                array $htmlOptions=array ( ))

$model      - the data model
$attribute  - the attribute
$htmlOptions- additional HTML attributes
{return}	- the generated input field

activeFileField With CHtml

Generate input file field using activeFileField function with model details

<?php echo  CHtml::activeFileField($model,'file_image'); ?>

fileField With Form

Generate input file field using fileField with form, model details

<?php echo  $form->fileField($model,'file_image'); ?>

fileField With CHtml (Without Model Name)

Generate input file field using fileFile without model details

<?php echo  CHtml::fileField('LoginForm[file_image]'); ?>


<input type="file" id="LoginForm_file_image" name="LoginForm[file_image]" value="" />

File In Controller

Using CUploadedFile::getInstance method, We can get the uploaded file in controller. Using saveAs($directory_with_filename) method, we can save the posted file. Yii have the magic method to get the file size, file extension name and more.

 public function actionFile()
    $filemodel=new Files;  
         if($model->file_image=CUploadedFile::getInstance($model,'file_image')) {

File Validation In Model

All Rules and validation in Yii Model

Leave a Reply

Your email address will not be published. Required fields are marked *