The error "cannot be empty" when saving () due to the rule of checking the "file"

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.

+4
source share
2 answers

It’s best not to use the same field for different purposes.

In your case, you are rewriting previewwith an instance UploadedFile, you can create another field for this, and then:

$model->previewFile = UploadedFile::getInstance($model, 'preview');

, save(), preview, previewFile, preview $model->validate().

+2

, , $_POST. $_FILES, - $_POST. , $_POST.

. , , :

public function actionCreate()
{
    $model = new Book();
    $model->load(Yii::$app->request->post());
    $model->scenario = 'create';
    $model->preview = UploadedFile::getInstance($model, 'preview');
    if ($model->validate()) {
        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,
        ]);
    }
}

, - .

P.S. , "skipOnEmpty" = > false, "" false.

+2

Source: https://habr.com/ru/post/1619031/


All Articles