Yii 1.1: File uploads in CForm (Form builder)


While there is a reasonable amount of documentation regarding CForm (form builder) and file uploads seperately, there really is not any coverage of both in combination.

The Model

First you will need a model: (FileUpload.php)

class FileUpload extends CFormModel {
    public $image;
     * @return array validation rules for model attributes.
    public function rules() {
        return array(
            //note you wont need a safe rule here
            array('image', 'file', 'allowEmpty' => true, 'types' => 'jpg, jpeg, gif, png'),

Note: for more information about validation rules, check Reference: Model rules validation

The CForm Array

Now you can build your CForm array: (uploadForm.php)

return array(
    'title' => 'Upload your image',
    'attributes' => array(
        'enctype' => 'multipart/form-data',
    'elements' => array(
        'image' => array(
            'type' => 'file',
    'buttons' => array(
        'reset' => array(
            'type' => 'reset',
            'label' => 'Reset',
        'submit' => array(
            'type' => 'submit',
            'label' => 'Upload',

The View

Your View: (upload.php)

<?php if (Yii::app()->user->hasFlash('success')): ?>
    <div class="info">
        <?php echo Yii::app()->user->getFlash('success'); ?>
<?php endif; ?>
<h1>Image Upload</h1>
<div class="form">
<?php echo $form; ?>

The Controller

And a controller and action:

class FileUploadController extends CController {
    public function actionUpload() {
        $model = new FileUpload();
    $form = new CForm('application.views.fileUpload.uploadForm', $model);
        if ($form->submitted('submit') && $form->validate()) {
            $form->model->image = CUploadedFile::getInstance($form->model, 'image');
            //do something with your image here
            Yii::app()->user->setFlash('success', 'File Uploaded');
        $this->render('upload', array('form' => $form));

At this point as best practice you would perform some work on the image in a method you write and call as a part of your FileUpload model. Note you don't have to assign anything to FileUpload::image but I do as a way of accessing it and having fat models/skinny controllers.

Total 2 comments

#11905 report it
Tofan Andrei at 2013/02/12 08:44am
Yii safe attribute issue

Please use:

array('image', 'file', 'allowEmpty' => true, 'safe'=>true, 'types' => 'jpg, jpeg, gif, png')

instead of

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

Ref: http://stackoverflow.com/questions/14731910/yii-form-builder

#6638 report it
jmariani at 2012/01/23 06:42pm

Thank you.

Leave a comment

Please to leave your comment.

Write new article