【问题标题】:Yii2 Call to a member function saveAs() on a non-objectYii2 在非对象上调用成员函数 saveAs()
【发布时间】:2016-02-07 14:08:52
【问题描述】:

所以我通过 doiteasychannel 在 youtube 上遵循 Yii2 教程,但是单击提交按钮时出现以下错误。

Call to a member function saveAs() on a non-object

以下是控制器操作中的一些代码,我创建了表单并添加了 enctype,但仍然报错。

下面的代码应该将文件保存到一个目录,然后将文件的路径添加到我的表格的头像列中。

$userprofile = UserProfile::findOne(['user_id' => $id]);     

$imageName = $user->username;
$userprofile->file = UploadedFile::getInstance($userprofile, 'file');
$userprofile->file->saveAs('uploads/'.$imageName.'.'.$userprofile->file->extension);
$userprofile->avatar = 'uploads/'.$imageName.'.'.$userprofile->file->extension;
$userprofile->user_id = Yii::$app->user->id;
$userprofile->save(false);

【问题讨论】:

    标签: php yii2 yii2-advanced-app


    【解决方案1】:

    请在您的UserProfile 模型中声明一个属性(变量)file 并在rules() 方法中分配其验证规则 - reference

    <?php
    
    namespace app\models;
    
    use Yii;
    
    /**
     * This is the model class for table "user". (for eg)
     *
     * ...
     */
    class UserProfile extends \yii\db\ActiveRecord
    {
        // for file uploading
        public $file;
    
        public function rules()
        {
            return [
                // ... other attribute validation rules
                [['file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
            ];
        }
    
        /**    
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'user'; // for eg
        }
    
        // ... rest of the code
    

    【讨论】:

    • 干杯我找到了解决方案,但它和你上面得到的完全一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2012-04-20
    • 2015-05-01
    相关资源
    最近更新 更多