In the update action of my users controller, I would like to put logic of re-sending a verification email if the user changes his/her email address. For this I need the app to remember the old email to check if it is different. Of course I could remember the email in a simple variable but I decided to instead use separate AR instances for the original user data and the modified user data, for flexibility and future enhancement.
I found however that Yii thinks that the save() being performed is an insert instead of an update. I was able to solve this however by setting $updatedUser->isNewRecord = false;
Here is my full code:
<?php public function actionUpdate() { $user = User::model()->findbyPk(isset($_GET['id']) ? $_GET['id'] : Yii::app()->user->id); if (empty($user)) throw new CHttpException(404, 'User cannot be found.'); if (isset($_POST['User'])) { $updatedUser = new User; $updatedUser->id = $user->id; $updatedUser->isNewRecord = false; $updatedUser->setAttributes($_POST['User'], 'update'); if ($updatedUser->validate('update')) { // email logic here // // if ($updatedUser->email!=$user->email) {send verification email logic}; if ($updatedUser->save(false)) $this->redirect(array('show')); } } $this->render('update', array('user' => $user)); }
Wouldn't it make sense though if Yii automatically knew it was an update instead of an insert because the pk was set? Just a suggestion… I believe CakePHP uses this logic.
Also, it seems that save() returns false if no rows were updated (for instance if the user presses "submit" without actually changing any fields). This does not seem to be noted in the documentation and confused me for a bit. This can be a nice feature, but now I don't know how my app should know the difference between a mysql error and no rows being updated. I would like the page to redirect in my example regardless of whether the user changed any fields.
Perhaps instead of updateByPk() returning the affected rows, the affected rows should be stored in an AR attribute such as $model->affectedRows or returned in a function? This is what CakePHP does: http://api.cakephp.o…3038f835e192fc3