L
L
Leopandro2015-12-08 13:06:11
Yii
Leopandro, 2015-12-08 13:06:11

Why does it say cannot be blank(when uploading a file)?

Here is a function in the controller responsible for creating a record

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

rules in the form:
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]
        ];
    }

But it's worth removing the script, everything works fine:
public function actionCreate()
    {
        $model = new Book();
        //$model->scenario = 'create';
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->preview = UploadedFile::getInstance($model, 'preview');
            $model->preview->saveAs('uploads/' . $model->preview->baseName . '.' . $model->preview->extension);
            if ($model->save())
            {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry Bay, 2015-12-08
@kawabanga

1) Because your preview field is required
2) you may not have it specified in the form - enctype="multipart/form-data" , check the incoming data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question