I'm trying to learn how to upload an image file in Yii. I'm using this code
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
in ProjectFile/views/site/upload.php file. The problem is in
<?= $form->field($model, 'imageFile')->fileInput() ?>
$model gives me a red underline. I have looked many examples and all of them wrote the like this. What I need to do stop this problem?
Edit: Is inside the controller/SiteController.php
// function for upload
public function actionUploadImage()
{
$model = new UploadImageForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
Is inside of models/UploadImageForm.php
<?php
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadImageForm extends \yii\base\Model
{
public $imageFile;
// gives rules of how to upload picture
public function rules(){
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
// uploads picture
public function upload(){
if($this->validate()){
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
}
}
}
In views\upload.php the red underline is shown because the system can't find the $model. While running, program will connect $model to controller. So the red underline is not a problem for php files.