I’m currently trying to follow the guide 2.0 on uploading multiple files but have run into a snag. First, my controller is as follows:
public function actionAddPhotos($id){
$listing_model = $this->findModel($id);
$upload_model = new ImageUploadForm();
if(Yii::$app->request->isPost){
$upload_model->imageFiles = UploadedFile::getInstance($upload_model,'imageFiles');
if($upload_model->upload()){
return $this->redirect('index');
}
}
return $this->render('add-listing-photos',[
'upload_model' => $upload_model,
'listing_model' => $listing_model
]);
}
my model is as follows
<?php
namespace common\models;
use yii\base\Model;
use yii\web\UploadedFile;
class ImageUploadForm extends Model{
/**
* @var UploadedFile[]
*/
public $imageFiles;
public function rules(){
return [
[['imageFiles'], 'file','skipOnEmpty' => false, 'extensions' => 'png, jpeg', 'maxFiles' => 15],
];
}
public function upload(){
if($this->validate()){
foreach($this->imageFiles as $file){
$file->saveAs('uploads/'.$file->baseName.".".$file->extension);
}
return true;
}else{
return false;
}
}
}
and finally my view is like so
<?php
$form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data'
]
]);
?>
<?= $form->field($upload_model, 'imageFiles[]')
->fileInput(['multiple' => true, 'accept' => 'image/*'])
?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
Now when I try to run this I get a validation error saying I must select a file…
I tried debugging the code and realized that the step
$upload_model->imageFiles = UploadedFile::getInstance($upload_model,'imageFiles');
is not assigning any value to my model saying
'imageFiles => null'
. I check and I do have the namespace yii\web\UploadedFile declared in the controller and the model class.
I even checked my php.ini settings
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads=On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir="C:\xampp\tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=10M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=20
Is there something I’m missing here???
Would appreciate any help on this matter. Thanks