简体   繁体   中英

How to update user using SignupForm.php Model in YII2?

How to make update form using SignupForm.php in yii2 ( Advanced Template ) for helping users to update their data?

I don't want to use any external modules.

I have in SignupForm.php Model:

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.');
    }
}

I have SiteController.php Controller :

 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,
    ]);
}

could be this action is what you are looking for

public function actionUpdate()
{
    if (Yii::$app->user->isGuest) {
        return $this->goHome();
    }

and for the password you need a function like this

    $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,
        ]);
    }
}

For the passwrod you can't simply assign the value but you must update the value with a function like like setPassword with another variable

public function updatePassword($new_password) {
   $this->password_hash =   Yii::$app->security
          ->generatePasswordHash($new_password);

}

Adapt the field name to your need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM