Hello,
I am trying to upload a file and it works fine when the input fields are populated properly by the user.
However, when the file field is left empty, an exception is thrown when I try to work with the file, because I have no validation rules for the field, other than a check to see whether it is a file, and everything fails if no file is specified.
When I include the file input field in the ‘required’ section of rules() in the model, the field is shown to be empty after submitting the form even when it is specified. The other fields of the form work fine, only the file input field fails.
Here are the rules:
public function rules()
{
return [
[['name', 'keywords', 'gameSource', 'cover'], 'required'],
[['keywords'], 'string'],
[['name'], 'string', 'max' => 50],
['game_categories_id', 'safe'],
[['gameSource', 'cover'], 'file'],
// [['gameSource', 'cover'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
];
}
This is the action:
public function actionCreate()
{
$model = new Games();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
//TODO: handle empty field errors for gameSource and cover
$game = UploadedFile::getInstance($model, 'gameSource');
$gameFileName = time().'.'.$game->extension;
$game->saveAs('games/'.$gameFileName);
...
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
The view:
<?php $form = ActiveForm::begin([
'options'=>[
'class'=>'',
'enctype'=>'multipart/form-data'
],
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'gameSource')->fileInput() ?>
...
Why is gameSource always empty when there is a ‘required’ rule for it, but works fine without it? The other fields, for which there is a ‘required’ rule, work fine.