简体   繁体   English

当ajax验证时,Yii2上传字段始终为空

[英]Yii2 upload field always empty when ajax validation

I have problem with upload file. 我上传文件有问题。 I use kartik-v/yii2-widget-fileinput extension. 我使用kartik-v / yii2-widget-fileinput扩展名。 Here my code: 这是我的代码:

form model rule 形式模型规则

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['image'], 'required', 'on' => static::SCENARIO_CREATE],
        [['image'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxSize' => 1024 * 1024],
    ];
}

form view 表单视图

<?php $form = ActiveForm::begin([     
    'enableAjaxValidation' => true,
    'options' => ['enctype' => 'multipart/form-data']
]); ?>

 <?= $form->field($model, 'image')->widget(FileInput::classname(), [
            'options' => ['accept' => 'image/*'],
            'pluginOptions' => [
                'showPreview' => false,
                'showCaption' => true,
                'showRemove' => true,
                'showUpload' => false,
                'showCancel' => false
            ],            
        ]); ?>

controller action 控制器动作

 public function actionCreate()
{
    $model = new ItemForm();
    $model->scenario = ItemForm::SCENARIO_CREATE;

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

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

        $image = UploadedFile::getInstance($model, 'image');

        $randomString = Yii::$app->getSecurity()->generateRandomString(10);
        $name = Inflector::slug($model->title) . '_' . $randomString . '.' . $image->extension;

        $url = Image::URL . $name;

        $model->image = $name;          

        if ($model->save()) {
            $image->saveAs($url);
            return $this->redirect(['view', 'id' => $model->id]);
        }       
    } else {         
        return $this->render('create', [
            'model' => $model,             
        ]);
    }
}

Always when I submit form, I got error "image field is required". 总是在我提交表单时,我收到错误“需要图像字段”。 I have read many tutorials but still I have the same problem when I using ajax validation. 我已阅读了很多教程,但在使用ajax验证时仍然遇到同样的问题。 Can anyone look at it and tell me what I'm doing wrong? 谁能看到它并告诉我我做错了什么?

EDIT 编辑

Above all you should not use enableAjaxValidation option if you have a file type field in your form. 最重要的是,如果表单中有文件类型字段,则不应使用enableAjaxValidation选项。 see this ISSUE use enableClientValidation instead 请参阅此ISSUE而是使用enableClientValidation

Apart from that looking at your complete model it looks like you are trying to use the database table field image as the same field to upload images where as you should not do that you should declare a custom field inside your model and use it to upload the file and assign the new filename to the database field image currently you have to do some additions in your model and changes to the code 除了查看完整模型之外,看起来您正在尝试使用数据库表字段image作为相同字段上传图像而不应该这样做,您应该在模型中声明自定义字段并使用它来上传文件并将新文件名分配给数据库字段image目前您必须在模型中添加一些内容并更改代码

1. Declare a custom field with the name $file like below on top of your model after public $tags like this, public $myFile; 1.在这样的public $tags之后,在你的模型顶部声明一个名为$file的自定义字段, public $myFile;

2. Change your validation rule 2.更改验证规则

[['image'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxSize' => 1024 * 1024],

to the following 以下

[['myFile'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxSize' => 1024 * 1024],

and

[['image'], 'required', 'on' => static::SCENARIO_CREATE],

to this 对此

[['myFile','image'], 'required', 'on' => static::SCENARIO_CREATE],

3. Change your field name in the html form, from image to myFile ie $form->field($model, 'image') to $form->field($model, 'myFile') . 3.在html表单中更改字段名称,从imagemyFile$form->field($model, 'image')$form->field($model, 'myFile')

4. For changes inside the action and uploadItemImage() function see below i have updated them. 4.对于actionuploadItemImage()函数内部的更改,请参见下文,我已更新它们。


you are assigning the $name variable to the $model->image field 您将$name变量分配给$model->image字段

 $model->image = $name; 

and in the $name it is a string, whereas in the model it should be a file 并且在$name它是一个字符串,而在模型中它应该是一个文件

 $name = Inflector::slug($model->title) . '_' . $randomString . '.' . $image->extension;

what you should be doing is assign the instance of the uploaded file to the model field image and then call the $model->save() and use the custom filename to saveAs() , change your action code to the following 您应该做的是将上传文件的实例分配给模型字段image ,然后调用$model->save()并使用自定义文件名saveAs() ,将您的action代码更改为以下

public function actionCreate()
{
    $model = new ItemForm();
    $model->scenario = ItemForm::SCENARIO_CREATE;

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

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

        $model->myFile = UploadedFile::getInstance($model, 'myFile');
        $randomString = Yii::$app->getSecurity()->generateRandomString(10);
        $model->image = Inflector::slug($model->title) . '_' . $randomString . '.' . $model->myFile->extension;

        $model->uploadItemImage();
        if ($model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }       
    } else {         
        return $this->render('create', [
            'model' => $model,             
        ]);
    }
}

and then create the following method inside your model 然后在模型中创建以下方法

public function uploadItemImage(){
    $url = Image::URL . $this->image;
    if(!$this->myFile->saveAs($url)){
       $this->addError('myFile','Unable to save the uploaded file');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM