We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon Model: Updating data from afterUpdate()

I wrote some code to send confirmation email to user in model, within afterUpdate(). I want to add an entry into database after sending the email. So I wrote the block this way

public function **afterUpdate()**
{
    ......
    ..........
    ......
        $sent = $mail->send($message, $subject, $this->Users->email, $this->Users->name);
        if($sent){
            $this->aprv_email_sent = 1;
            $this->update();
        }

    }

}

Unfortunately that wasn't working. I know I can update through beforeUpdate(). But I want to send email after updating main records into database.

Please advice me.



85.5k
edited Sep '15

maybe


if ($record->save() !== false ){
    $send-> .....
    $record->aprv_email_sent = 1;
    $record->save();
}

This might be blocked by Phalcon blocked. If it wasn't, you'd have created an infinite loop there.

edited Sep '15

Here is how I did mine in my User model:

/**
 * Send a confirmation e-mail to the user if the account is not active
 */
public function sendEmailConfirmation($id, $email)
{
    $user = self::findUserById($id);
    if($user){
        $user->usr_email = $email;
        $save = $user->save();

        if ($save && $user->usr_email_verified == 0) {
            $emailConfirmation = new EmailConfirmations();
            $emailConfirmation->usersId = $user->usr_id;
            $success = $emailConfirmation->save();

            return $success;
        }
    }
}  

Since here I saved the record, then in my EmailConfirmations.php I do all the email sending with aftercreate(); .

Just an example and I thought this might help.