I got this error when the image file is required: "Preview cannot be empty." Although I filled out this field.
My rules:
public function rules()
{
return [
[['name', 'preview', 'date', 'author_id'], 'required', 'on' => 'update'],
[['name', 'preview', 'date', 'author_id'], 'required', 'on' => 'create'],
[['date_create', 'date_update', 'author_id'], 'integer'],
[['preview'], 'file', 'skipOnEmpty' => 'false', 'extensions' => 'png, jpg, jpeg'],
[['date'], 'safe'],
[['name'], 'string', 'max' => 255]
];
}
Controller:
public function actionCreate()
{
$model = new Book();
$model->scenario = 'create';
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->preview = UploadedFile::getInstance($model, 'preview');
if ($model->save() && $model->preview->saveAs('uploads/' . $model->preview->baseName . '.' . $model->preview->extension))
{
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
If the file is previewnot required, there is no error, and the file is downloaded to the folder uploads.