I am using kartik file input extension and have setup my form for multiple file upload(https://github.com/kartik-v/yii2-widget-fileinput) (note not using ajax)
I am stuck on how to change the model function upload image to loop through the array and store the image filename.
Currently this line
$this->logo_filename = $image->name;
causes this error
Trying to get property of non-object
Using
var_dump($image);
in my model I get the following output
array(2) { [0]=> object(yii\web\UploadedFile)#96 (5) { ["name"]=> string(22) "someimage.png" ["tempName"]=> string(36) "/Applications/MAMP/tmp/php/phpjj5mZr" ["type"]=> string(9) "image/png" ["size"]=> int(1585) ["error"]=> int(0) } [1]=> object(yii\web\UploadedFile)#97 (5) { ["name"]=> string(18) "someimg.png" ["tempName"]=> string(36) "/Applications/MAMP/tmp/php/phpHAMgEz" ["type"]=> string(9) "image/png" ["size"]=> int(1777) ["error"]=> int(0) } }
Model
public function uploadImage() {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array (you may need to use
// getInstances method)
$image = UploadedFile::getInstances($this, 'image');
var_dump($image);
// if no image was uploaded abort the upload
if (empty($image)) {
return false;
}
//need some foreach loop
// store the source file name
$this->logo_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name
$this->logo_img = Yii::$app->security->generateRandomString().".{$ext}";
// the uploaded image instance
return $image;
}
Controller - Does the controller and/or need the foreach loop to save the images
public function actionCreate()
{
$model = new ProductBrand();
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadImage();
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false) {
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', 'id'=>$model->id]);
} else {
// error in saving model
}
}
return $this->render('create', [
'model'=>$model,
]);
}