yii2.0 讀取user表新增字段問題

最近修改user表字段,在自帶的user表中新增一個渠道權限,user類修改的地方以下:前端

展現的轉化爲漢字顯示,定義channel的規則:app

 public function attributeLabels(){
        return [
            'id'        => 'ID',
            'username'    => '用戶名',
            'created_at'=> '註冊時間',
            'updated_at'=> '修改時間',
            'channel'=> '渠道',
        ];
    }
public function rules() { return [ ['username', 'filter', 'filter' => 'trim'], ['username', 'required'], ['username', 'unique', 'message' => 'This username has already been taken'], ['username', 'string', 'min' => 2, 'max' => 255], ['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'string', 'max' => 255], ['email', 'unique', 'message' => 'This email address has already been taken'], [['password'], 'required', 'on' => ['create']], [['password'], 'string', 'min' => 6, 'on' => ['create', 'update']], ['status', 'default', 'value' => self::STATUS_ACTIVE], ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]], [['channel'], 'safe'], ]; }
public function signup() { if (!$this->validate()) { return null; } $this->username = $this->username; $this->email = $this->email; $this->channel = implode(',',$this->channel);//定義了channel safe以後才能夠用$this->channel訪問數據 $this->setPassword($this->password); $this->generateAuthKey(); return $this->save() ? $this : null; }

前端頁面展現用的是複選框展現:post

    <?= $form->field($model, 'channel', [
                    'labelOptions' => ['class'=>'col-lg-2 control-label'],
                    'template' => '
                    {label}
                    <div class="col-lg-10">
                    {input}
                    {error}
                    </div>
                    ',
                ])->checkboxList($gamechannel) ?>

遇到的問題:ui

一、在signup保存數據的時候$this->channel訪問返回NULL,設置rules channel safe 以後就能夠用$this訪問,沒有設置以前能夠用['User']['channel']訪問。this

二、編輯頁面展現,db裏存在的channel要展現被選中狀態。spa

 public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('update');
        if($model->load(Yii::$app->request->post())){
            if($model->password){
                $model->setPassword($model->password);
                $model->generateAuthKey();
            }
            if($model->channel){
                $model->channel = implode(',',$model->channel);
            }

            if ($model->save()) {
                return $this->redirect(['index']);
            } else {
                return $this->render('//user/update', [
                    'model' => $model,
                ]);
            }
        }else{
            $checklist = explode(',',$model->channel);
            $model->channel = $checklist;  //就是這裏 從db裏讀取渠道賦值給$model->channel
            return $this->render('//user/update', [
                'model' => $model,
            ]);
        }
    }

 

相關文章
相關標籤/搜索