[英]How to update user using SignupForm.php Model in YII2?
如何使用yii2( Advanced Template
)中的SignupForm.php制作更新表单以帮助用户更新其数据?
我不想使用任何外部模块。
我在SignupForm.php模型中:
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->first_name = $this->first_name;
$user->last_name = $this->last_name;
$user->sub_id = $this->sub_id;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->status=10;
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
}
return null;
}
public function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
我有SiteController.php控制器:
public function actionProfile()
{
if (Yii::$app->user->isGuest) {
return $this->goHome();
}
$id = Yii::$app->user->id;
$model = SignupForm::findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['/event/index']);
} else {
return $this->redirect(['user/view/?id='.$id]);
}
}
public function actionSignup()
{
$this->layout = 'loginlayout';
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
可能是您要寻找的动作
public function actionUpdate()
{
if (Yii::$app->user->isGuest) {
return $this->goHome();
}
对于密码,您需要这样的功能
$id = Yii::$app->user->id;
$model = SignupForm::findModel($id);
if ($model->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['/event/index']);
} else {
return $this->render('signup', [
'model' => $model,
]);
}
}
对于密码,您不能简单地分配值,但必须使用诸如setPassword之类的函数通过另一个变量来更新值
public function updatePassword($new_password) {
$this->password_hash = Yii::$app->security
->generatePasswordHash($new_password);
}
根据您的需要修改字段名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.