Yii 1.1: Multiple file upload handler

7 followers

Hi,

Recently I've worked on a project where I had to upload multiple files. I've come up with a short generalized script. You can use it if you have a table with lot of file location fields/columns. I don't know if it's the best solution or not but it works great for me. so, lets start

in your controller you need to call myFileHandler function with only file upload fields.

so, it will be

public function actionIndex(){
 
........
........
 
  $model = $this->myFileHandler($model, array('logo','emailus_img','emailus_img_hover','more_img','more_img_hover','gomo_logo','mobile_phone_img','animate_on_mobile_img','animate_above_text_img','animate_under_text_img','bottom_right_img'));
 
.......
.......
}
public function myFileHandler($model, $imgFieldNameArr){
 
  foreach($imgFieldNameArr as $attribute){
    $instance = CUploadedFile::getInstance($model, $attribute);
 
    if($instance){
      $fullImgName = time().'_'.$attribute.'.'.$instance->getExtensionName();   
      $fullImgSource = Yii::getPathOfAlias('webroot').'/media/images/'.$fullImgName;    
 
      $instance->saveAs($fullImgSource);    
      $model->$attribute = $fullImgName;
    }
  }
  return $model; //return model with updated file path
}

I hope this little tricks will help you.

Total 2 comments

#6868 report it
hasanavi at 2012/02/09 05:30pm
for updating...

Hi,

Thanks for your reply. Yes, when its time to update if the file field is empty it also make the attribute empty. To overcome this, I've loaded another model with the same id and update the new model attribute with the old model attribute value, if file is not uploaded.

$oldRecord = $this->loadModel($id);
 
if($instance){
  // file upload code...
  $model->$attribute = $fullImgName;
}else{
   $model->$attribute = $oldRecord->$attribute;
}

Feel free to update the wiki after your testing if you find better solution.

#6855 report it
redguy at 2012/02/09 08:07am
...as behavior

I am developing similiar pattern with behavior. What it does additionaly is pre-fill attributes on beforeValidate to make validation possible and actually save files on afterSave (when the record is saved properly to db). You can also provide prefixes/postfixes for every atribute. there is also one more feature - by default file upload field resets model attribute when there is no file uploaded. My solution is to attach form controll to some other virtual attribute (eg. file_upload) process and validate this attribute and save file name to "file" attribute only when there is proper file uploaded. I am testing this right now and then I could post this behavior...

Leave a comment

Please to leave your comment.

Write new article