Reputation: 1686
Now, i have an update form with three inputs - username, email and password. Everything is ok except the case when i try to update only the password.
For example: Username and email of the user have to stay the same and only the password must be changed. And here what is happening:
In this case i am trying to update only the password of the user. Controller actionUpdate:
public function actionUpdate()
{
$model = new UpdateForm();
$id = \Yii::$app->user->identity->id;
$user = $this->findModel($id);
//default values
$model->username = $user->username;
$model->email = $user->email;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if (isset($_POST['UpdateForm']))
{
$model->attributes = $_POST['UpdateForm'];
if($model->validate())
{
$user->username = $model->username;
$user->email = $model->email;
$user->password = md5($model->password);
$user->update();
$this->redirect(['view', 'id' => $user->id]);
}
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
UpdateForm model rules:
public function rules()
{
return [
[['email', 'password', 'username'], 'required'],
[['email', 'password', 'username'], 'string', 'max' => 50],
[['image'], 'string', 'max' => 255],
[['username', 'password', 'email'], 'trim'],
['email', 'email'],
[[ 'email', 'username'], 'unique',
'targetAttribute' => ['email', 'username'],
'message' => 'The combination of username and password is already taken'],
];
}
Appreciating every advice! Thank you in advance!
Upvotes: 0
Views: 570
Reputation: 133380
Try using save() instead of update()
if (isset($_POST['UpdateForm']))
{
$model->attributes = $_POST['UpdateForm'];
if($model->validate())
{
$user->username = $model->username;
$user->email = $model->email;
$user->password = md5($model->password);
$user->save();
$this->redirect(['view', 'id' => $user->id]);
}
}
Upvotes: 0