Hi,
I have tree related models users
& courses
& EmailConfirmations
as follow:
Users -> hasManyToMant -> Courses
Users-> hasMany -> EmailConfirmations
In my Users model I have afterCreate method:
/**
* Send a confirmation e-mail to the user if the account is not active
*/
public function afterCreate()
{
if ($this->isActive == self::NOT_ACTIVE) {
$emailConfirmation = new EmailConfirmations();
$emailConfirmation->userId = $this->id;
if ($emailConfirmation->save()) {
$this->getDI()
->getFlashSession()
->notice('A confirmation mail has been sent to ' . $this->email);
} else {
$this->getDI()
->getFlashSession()
->error($emailConfirmation->getMessages());
}
}
}
and In EmailConfirmations, I have:
/**
* Send a confirmation e-mail to the user after save the user confirmation params
*/
public function afterCreate()
{
$this->getDI()
->getMail()
->send(array(
$this->user->email => $this->user->getFullName()
), "Please confirm your email", 'confirmation', array(
'confirmUrl' => 'confirm/' . $this->code . '/' . $this->user->email
));
}
In controller I'm trying to create a new user and assign a course to him:
$user = new Users();
$user->assign(array(
'firstName' => $this->request->getPost('firstName', 'striptags'),
'lastName' => $this->request->getPost('lastName', 'striptags'),
'email' => $this->request->getPost('email'),
'password' => $this->security->hash($this->request->getPost('password')),
'registeredIP' => $this->request->getClientAddress()
));
$course = new Courses();
$user->teachingCourses = array($course); // <-- many to many alias
if ($user->save()) {
return $this->dispatcher->forward(array(
'controller' => 'index',
'action' => 'index'
));
}
Problem is when there is an error in course insertion (such as missing model required fields and virtual foreignKey errors), all insertion rollback but afterCreate event in Users
model & EmailConfirmations
model calls and email sent to user without any record in confirmation table!
Why thoes events run if nothing inserted into tables, and what can I do to make this works?
Thanks