【问题标题】:Yii 2 : Trying to get property of non-object in Yii2Yii 2:试图在 Yii2 中获取非对象的属性
【发布时间】:2015-08-06 10:39:23
【问题描述】:

控制器

public function actionCreate()
    {
       $model = new RoomTypes();
        if ($model->load(Yii::$app->request->post())) {
            // get the uploaded file instance. for multiple file uploads
            // the following data will return an array
            $image = UploadedFile::getInstance($model, 'image');

            // store the source file name
            $model->room_type = $image->name;
            $imageName_1 = $model->room_type;
            $ext = end((explode(".", $image->name)));

            // generate a unique file name
            $model->pic_1 = Yii::$app->security->generateRandomString().".{$ext}";

            // the path to save file, you can set an uploadPath
            // in Yii::$app->params (as used in example below)
            $path = Yii::$app->params['uploadPath'] . $model->pic_1;

            if($model->save()){
                $image->saveAs($path);
                return $this->redirect(['view', 'id'=>$model->_id]);
            } else {
                // error in saving model
            }
        }
        return $this->render('create', [
            'model'=>$model,
        ]);
    }

型号:

public $image;

[['image'], 'safe'],
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],

查看

    <?= $form->field($model, 'room_type')->label(false)->textInput(['maxlength' => true]) ?>


    <?php echo $form->field($model, 'image[]')->widget(FileInput::classname(), [
                                              'options'=>['accept'=>'image/*', 'multiple'=>true],
                                              'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png']
'slugCallback' => new JsExpression(function(room_type) 
{return room_type;},),]]); 
                                        ?>

上传文件时出现此错误。 也不接受多张图片上传,这是怎么回事? 这种多文件上传怎么实现???

【问题讨论】:

  • 不要创建另一个变量 $image 只需使用 [['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles ' => 4],并循环它们以存储多个图像。
  • 做了更正,但仍然是同样的错误:(
  • 你能不能显示错误...
  • 它在控制器在线$model-&gt;room_type = $image-&gt;name;
  • 您必须确保您的Activeform 有一个option enctype =&gt; multipart/form-data 用于上传多个文件。

标签: php yii yii2


【解决方案1】:

您在示范规则中打印错误:

[['$image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],

应该是

[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多