微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – yii2 – Kartik文件输入 – 更新

情况就是这样:我是Yii2的新手,想在ActiveForm中使用一些文件上传器小部件..到目前为止,我发现这个非常好的一个\kartik\widget\FileInput

使用此小部件,我可以管理文件上传,然后,当进入编辑模式时,使用oportunite显示一个上传的图像以替换它.

问题是,如果我在没有修改图像的情况下按下表单的“更新”按钮,则表示图像“不能为空”,因为我在模型中设置了“必需”规则.

经历了一个糟糕的下午和更富有成效的夜晚之后,我遇到了一个我有用的解决方案.

主要问题是文件输入在更新时不发送其值(存储在数据库中的文件名称).它仅在浏览并通过文件输入选择时发送图像信息.

所以,我的解决方法是创建另一个用于管理文件上传的“虚拟”字段,名为“upload_image”.为此,我简单地将一个带有此名称的公共属性添加到我的模型类中:public $upload_image;

我还在Model类的规则方法添加了以下验证:

public function rules()
{
    return [
        [['upload_image'],'file','extensions' => 'png,jpg','skipOnEmpty' => true],[['image'],'required'],];
}

在这里,’upload_image’是我的虚拟列.我使用’skipOnEmpty’= true添加文件’验证,’image’是我数据库中的字段,在我的情况下必须是必需的.

然后,在我看来,我配置了’upload_image’小部件,如下所示:

echo FileInput::widget([
        'model' => $model,'attribute' => 'upload_image','pluginoptions' => [
            'initialPreview'=>[
                Html::img("/uploads/" . $model->image)
            ],'overwriteInitial'=>true
        ]
    ]);

在’initialPreview’选项中,我将我的图像名称设置为存储在从数据库返回的’$model-> image’属性中.

最后,我的控制器如下:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->load(Yii::$app->request->post());

    if(Yii::$app->request->isPost){
        //Try to get file info
        $upload_image = \yii\web\UploadedFile::getInstance($model,'upload_image');

        //If received,then I get the file name and asign it to $model->image in order to store it in db
        if(!empty($upload_image)){
            $image_name = $upload_image->name;
            $model->image = $image_name;
        }

        //I proceed to validate model. Notice that will validate that 'image' is required and also 'image_upload' as file,but this last is optional
        if ($model->validate() && $model->save()) {

            //If all went OK,then I proceed to save the image in filesystem
            if(!empty($upload_image)){
                $upload_image->saveAs('uploads/' . $image_name);
            }

            return $this->redirect(['view','id' => $model->id]);
        }
    }
    return $this->render('update',[
        'model' => $model,]);
}

原文地址:https://www.jb51.cc/php/130486.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐