Yii2 FileInput - 试图获取非对象的属性 [英] Yii2 FileInput - Trying to get property of non object

查看:38
本文介绍了Yii2 FileInput - 试图获取非对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Yii2 和 Kartik 的 FileInput 扩展,并且我已经成功地使文件上传工作(仅单个上传).我现在的问题是,如果我没有选择任何文件(它应该是可选的),我会收到标题中的错误(附有日志).

在互联网上进行大量搜索后,我认为这与数组有关,但我不知道如何解决这个问题,尤其是即使日志指向确切的行!

这是我的日志,

这是我的模型,

namespace app\models;使用 Yii;类 FormMovement 扩展 \yii\db\ActiveRecord{公共$文件;公共静态函数 tableName(){返回 '​​form_movement';}公共函数规则(){返回 [[['fm_date_received', 'fm_form_name', 'fm_from', 'fm_ptj'], 'required'],[['form_id'], '整数'],[['fm_date_received', 'fm_date_action1', 'fm_date_action2','fm_upload'], 'safe'],[['fm_form_name', 'fm_note'], 'string', 'max' =>500],[['fm_from', 'fm_ptj', 'fm_action1', 'fm_action2'], 'string', 'max' =>100],[['文件'],'文件','skipOnEmpty' =>真,'扩展'=>'jpg,pdf,png,doc,docx,xl​​s,xlsx,jpeg','maxFiles'=>3],];}

我的控制器功能,日志显示在第75行,就是这个,

$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;

一直在修修补补,但没有成功.

公共函数 actionCreate(){$model = new FormMovement();if ($model->load(Yii::$app->request->post())) {//设置文件名$fileName = $model ->fm_form_name;//获取实例$model->file = UploadedFile :: getInstance($model, 'file');//设置db中的文件路径$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;//保存文件到服务器目录$model->save();$model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);返回 $this->redirect(['view', 'id' => $model->form_id]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

最后我的观点,

<?= Html::activeLabel($model, 'file[]', ['标签'=>'MUAT NAIK 失败','class'='col-sm-1 控制标签']) ?><div class="col-sm-8"><?= $form->field($model, 'file',['showLabels'=>false])->widget(FileInput::classname(), ['选项' =>['接受' =>'文件/*', '多个' =>'真的'],'插件选项'=>['showUpload' =>错误的,]]) ?>

解决方案

这部分应该重构:

//设置文件名$fileName = $model ->fm_form_name;//获取实例$model->file = UploadedFile :: getInstance($model, 'file');//设置db中的文件路径$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;//保存文件到服务器目录$model->save();$model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);

像这样:

$model->file = UploadedFile::getInstance($model, 'file');$model->save();如果($模型->文件){$model->fm_upload = "上传/{$model->fm_form_name}.{$model->file->extension}";$model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");}

另请注意,您根本不会在控制器中处理失败的验证.

为了进一步重构,这一行:

$model->file = UploadedFile::getInstance($model, 'file');

可以移动到 beforeValidate() 事件处理程序.

这部分:

if ($model->file) {$model->fm_upload = "上传/{$model->fm_form_name}.{$model->file->extension}";$model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");}

可以移动到 afterSave() 事件处理程序以保持您的控制器纤薄.

saveAs() 中最好使用别名,我在这个 答案.

i am using Yii2 and Kartik's FileInput extension and I have successfully get the file uploads working(only single upload). My problem now is that, I get the error as in the title(with logs attached) if I did not choose any files(It should be optional).

After much searching over the internet, I think it has to be something to do with array, but I am not sure how to fix that, especially even with the logs pointing to the exact line!

Here is my log,

Here is my model,

namespace app\models;

use Yii;

class FormMovement extends \yii\db\ActiveRecord
{

    public $file;

    public static function tableName()
    {
        return 'form_movement';
    }

    public function rules()
    {
        return [
            [['fm_date_received', 'fm_form_name', 'fm_from', 'fm_ptj'], 'required'],
            [['form_id'], 'integer'],
            [['fm_date_received', 'fm_date_action1', 'fm_date_action2','fm_upload'], 'safe'],
            [['fm_form_name', 'fm_note'], 'string', 'max' => 500],
            [['fm_from', 'fm_ptj', 'fm_action1', 'fm_action2'], 'string', 'max' => 100],
            [['file'], 'file', 'skipOnEmpty' => true, 'extensions'=>'jpg,pdf,png,doc,docx,xls,xlsx, jpeg', 'maxFiles' => 3],
        ];
    }

My controller function, the log shows that it is at the line 75, which is this one,

$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;

Been tinkering with it, but no success.

public function actionCreate()
    {
        $model = new FormMovement();

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

            //set the file name
            $fileName = $model -> fm_form_name;

            //get instance
            $model->file = UploadedFile :: getInstance($model, 'file');

            //set the file path in the db
            $model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;

            //save the file to the server directory
            $model->save();
            $model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);

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

Finally my view,

<div class="form-group kv-fieldset-inline">
    <?= Html::activeLabel($model, 'file[]', [
            'label'=>'MUAT NAIK FAIL',
            'class'=>'col-sm-1 control-label'
        ]) ?>

    <div class="col-sm-8">
    <?= $form->field($model, 'file',[
                'showLabels'=>false
            ])->widget(FileInput::classname(), [
            'options' => ['accept' => 'file/*', 'multiple' => 'true'],
            'pluginOptions'=>[
                'showUpload' => false,
            ]
    ]) ?>
    </div>
</div>

解决方案

This part should be refactored:

//set the file name
$fileName = $model -> fm_form_name;

//get instance
$model->file = UploadedFile :: getInstance($model, 'file');

//set the file path in the db
$model->fm_upload='uploads/'.$fileName.'.'.$model->file->extension;

//save the file to the server directory
$model->save();
$model->file->saveAs('uploads/'.$fileName.'.'.$model->file->extension);

like this:

$model->file = UploadedFile::getInstance($model, 'file');
$model->save();

if ($model->file) {    
    $model->fm_upload = "uploads/{$model->fm_form_name}.{$model->file->extension}";    
    $model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");
}

Also note that you don't handle failed validation in your controller at all.

For further refactoring, this line:

$model->file = UploadedFile::getInstance($model, 'file');

can be moved to beforeValidate() event handler.

This part:

if ($model->file) {    
    $model->fm_upload = "uploads/{$model->fm_form_name}.{$model->file->extension}";    
    $model->file->saveAs("uploads/{$model->fm_form_name}.{$model->file->extension}");
}

can be moved to afterSave() event handler to keep your controller slim.

In saveAs() it's better to use alias, I desribed it in this answer.

这篇关于Yii2 FileInput - 试图获取非对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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