T
T
teodor7teodor72016-11-03 11:03:08
Yii
teodor7teodor7, 2016-11-03 11:03:08

How to fix yii2 file validation error?

It is not clear what the mistake is who faced.
the form

<?php
    $form = ActiveForm::begin([
                'id' => $model->formName(),
                'enableAjaxValidation' => true,
                'validationUrl' => Url::toRoute('validation-certificate-form'),
                'action' => Url::toRoute('certificate-form'),
                'options' => ['enctype' => 'multipart/form-data'],
        
    ]);
    ?>

public function rules() {
        return [
                [[
          'club_id',
 
            ], 'required'],
                ['certificate_code', 'unique', 'targetClass' => '\common\models\Certificate'],
   [['certificate_file'], 'file', 'extensions' => ['png', 'jpg'], 'skipOnEmpty' => false ]
        ];
    }

public function actionCertificateForm() {

        $modelCertificateForm = new CertificateForm();

        if ($modelCertificateForm->load(Yii::$app->request->post())) {

            $modelCertificateForm->certificate_file = UploadedFile::getInstance($modelCertificateForm, 'certificate_file');


            if ($modelCertificateForm->validate()) {

                if ($modelCertificateForm->save() && $modelCertificateForm->upload()) {


                    Yii::$app->session->setFlash('success', 'Сертификат успешно создан.');
                    return $this->refresh();
                } else {
                    var_dump($modelCertificateForm->upload())  ; die();
                    Yii::$app->session->setFlash('error', 'Ошибка сохранения сертификата.');
                    return $this->render('index', ['model' => $modelCertificateForm]);
                }
            } else {
                return $this->render('index', ['model' => $modelCertificateForm]);
            }
        } else {
            return $this->render('index', ['model' => $modelCertificateForm]);
        }
    }

when adding a file, add file is displayed. After we remove 'enableAjaxValidation' => true, client-side validation is fine. How to fix it? or remove Ajax validation for a file?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2016-11-03
@webinar

With ajax validation, the file is not transferred, so the error.
I think the problem is that you are not uploading the file correctly. You need to have a public variable file in the model into which the file itself will fall, remove 'skipOnEmpty' => false from it, and set the certificate_file validator string into which the file name will fall and now make it mandatory, since you will get into the database just the name, not the whole file.
Example here:
www.yiiframework.com/doc-2.0/guide-input-file-uplo...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question