Monday, February 13, 2012

Make upload file in yiiframework

Upload file in yiiframework is easy than the others. Simple to use this, you can use the functions of saveAs in yiiframework. Oke let's suppose you have a table like this :

t_users            
id_user              varchar(30)
profile_picture   varchar(100)
name                  varchar(50)

You can use gii to generate the model and the CRUD form. and then if you have already have those files. And now you can go to your form to edit the form like this. Don't forget to add the htmlOptions as multipart form data like below.

<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'tuser-form',
 'enableAjaxValidation'=>false,
 'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">
 Fields with <span class="required">*</span> are required.
</p>

<?php echo $form->errorSummary($model); ?>
 <div class="row">
  <?php echo $form->labelEx($model,'profile_picture'); ?>
  <?php echo $form->fileField($model,'profile_picture',array('size'=>60,'maxlength'=>200)); ?>
  <?php echo $form->error($model,'title'); ?>
 </div>
 

And then in your TUserController just update the actionUpdate and actionCreate like this ::

$model->attributes=$_POST['TUser'];
 $model->profile_picture=CUploadedFile::getInstance($model, 'profile_picture');
 if($model->save()){
  if(strlen($model->profile_picture)>0)
   $model->profile_picture->saveAs(Yii::app()->basePath.'/../upload/'.$model->profile_picture);
  $this->redirect(array('view','id'=>$model->id_user));
 }
Oke tha's so simple to create an upload for yiiframework..

if you want to make some filter of your files use the rules in your model, in this case is TUser model..

like this


public function rules()
    {
        return array(
            array('picture_profile', 'file', 'types'=>'jpg, gif, png'),
           ...
        );
    }

Yii is Rock..

3 comments:

  1. Dude You rock!! i've been looking how to upload files for ages!!!!!

    can you write another post about how to modify the actionUpdate? it should pull the original files back in and ask for replace if new file uploaded.

    ReplyDelete
  2. Oke dude I will post next time.. But not now..

    ReplyDelete
  3. Thanks for the Post. It really worked for me specially :)

    ReplyDelete