编程语言
首页 > 编程语言> > php-Yii2上传字段在ajax验证时始终为空

php-Yii2上传字段在ajax验证时始终为空

作者:互联网

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

表格模型规则

/**
 * @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验证时仍然遇到相同的问题.有人可以看一下,告诉我我在做什么错吗?

解决方法:

编辑

最重要的是,如果表单中有文件类型字段,则不应使用enableAjaxValidation选项.看到此ISSUE,请改用enableClientValidation

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

1.在像这样的公共$标记public $myFile之后,在模型顶部声明一个名称为$file的自定义字段,如下所示:

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’).

4.对于action和uploadItemImage()函数内部的更改,请参见下文,我已对其进行了更新.

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

 $model->image = $name; 

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

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

您应该做的是将上传文件的实例分配给模型字段图像,然后调用$model-> save()并使用自定义文件名将其保存为saveAs(),将操作代码更改为以下内容

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

然后在模型中创建以下方法

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

标签:image-uploading,php,file-upload,yii2
来源: https://codeday.me/bug/20191014/1912141.html