yii2.0 读取user表新增字段问题
最近修改user表字段,在自带的user表中新增一个渠道权限,user类修改的地方如下:
展示的转化为汉字显示,定义channel的规则:
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; }
前端页面展示用的是复选框展示:
<?= $form->field($model, 'channel', [ 'labelOptions' => ['class'=>'col-lg-2 control-label'], 'template' => ' {label} <div class="col-lg-10"> {input} {error} </div> ', ])->checkboxList($gamechannel) ?>
遇到的问题:
1、在signup保存数据的时候$this->channel访问返回NULL,设置rules channel safe 之后就可以用$this访问,没有设置之前可以用['User']['channel']访问。
2、编辑页面展示,db里存在的channel要展示被选中状态。
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, ]); } }