Ajax验证时Yii2上传字段始终为空 [英] Yii2 upload field always empty when ajax validation

查看:182
本文介绍了Ajax验证时Yii2上传字段始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上传文件时遇到问题.我使用kartik-v/yii2-widget-fileinput扩展名.这是我的代码:

I have problem with upload file. I use kartik-v/yii2-widget-fileinput extension. Here my code:

表单模型规则

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

表单视图

<?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
            ],            
        ]); ?>

控制器动作

 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,             
        ]);
    }
}

总是在我提交表单时出现错误图像字段为必填项".我已经阅读了许多教程,但是当我使用Ajax验证时仍然遇到相同的问题.有人可以看一下,告诉我我在做什么错吗?

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. Can anyone look at it and tell me what I'm doing wrong?

推荐答案

编辑

首先,如果表单中有文件类型字段,则不应该使用enableAjaxValidation选项.参见 ISSUE 代替,使用enableClientValidation

Above all you should not use enableAjaxValidation option if you have a file type field in your form. see this ISSUE use enableClientValidation instead

除了查看完整的模型之外,您似乎还想将数据库表字段image用作同一字段来上传图像,而您不应该这样做,则应该在模型内部声明一个自定义字段,使用它来上传文件并将新文件名分配给数据库字段image,当前您必须在模型中进行一些添加并更改代码

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

1..在这样的public $tagspublic $myFile;

2..更改验证规则

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

到以下

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

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

对此

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

3..以html格式将字段名称从image更改为myFile,即将$form->field($model, 'image')更改为$form->field($model, 'myFile').

3. Change your field name in the html form, from image to myFile i.e $form->field($model, 'image') to $form->field($model, 'myFile').

4..对于actionuploadItemImage()函数内部的更改,请参见下面的内容,我已经对其进行了更新.

4. For changes inside the action and uploadItemImage() function see below i have updated them.

您正在将$name变量分配给$model->image字段

you are assigning the $name variable to the $model->image field

 $model->image = $name; 

,在$name中,它是一个字符串,而在模型中,它应该是一个文件

and in the $name it is a string, whereas in the model it should be a file

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

您应该做的是将上载文件的实例分配给模型字段image,然后调用$model->save()并将自定义文件名更改为saveAs(),将您的action代码更改为以下

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

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');
    }
}

这篇关于Ajax验证时Yii2上传字段始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆