I have been writing a component recently that I need to send a system email out when a NEW record is created to the logged in user. I thought I would share how to do it in case its of use to anyone.
Summary
+++++++
I have a component that I will just call for the sake of this tutorial 'MYCOMP'
I have a table called 'Distributors' which has a view 'editdistributorprofile'
User create a profile and then get send an email to let them know the profile is being approved (the email also goes to a fix list of admins, but I will leave that out as I am sure you can replicate this work to add extra emails
1) I added the following to my language file for the component installer, though you can just as easily create language overrides in the Joomla backend (EXTENSIONS->LANGUAGE->OVERRIDES)
MYCOMP_MAILER_DISTRIBUTORPROFILE_SUBJECT = "Your profile is being approved"
MYCOMP_MAILER_DSITRIBUTORPROFILE_BODY = "The admin team will evaluate your profile and get back to you"
2) I FORK the distributor model
3) I copy the
public function save($data) function to my model
4) Find the section in your model
if (parent::save($data)) {
return true;
}
return false;
This is where the magic (or any post save magic) happens. Not specific to this task but a great tip.. you can do things after any save, and its really easy to distiguish between a NEW record and an UPDATED one by the passing of ID. I only want to send a mail if the recrod added is NEW (i,e saved with no id file) so I need to add
if (parent::save($data)) {
// Check if ID file has NOT been defined
if (!$data['id']) {
// Do something if Id is not defined
}
return true;
}
return false;
Of course this means if ID is defined, the save function just returns true as normal and does nothing different
You could just as easily use
// If NEW
if ($data['id']) {
// do something if record is just being updated
} else {
// do something if record is new
}
if you want to do something for both eventualities.. but I dont need that.
Anyways, I wont go into the details of the mailers which are covered in detail HERE (if you want to add images and attachments etc) but here is the final code which sends a mail to the user when the new record is created
if (parent::save($data)) {
//Check if NEW or UPDATE
// If NEW
if (!$data['id']) {
// Initialise Mailer
$mailer = JFactory::getMailer();
//Set sender as system
$config = JFactory::getConfig();
$sender = array(
$config->get( 'mailfrom' ),
$config->get( 'fromname' )
);
$mailer->setSender($sender);
// Get logged in users mail as RECIPIENT
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
// Content
$body = JText::_( 'MYCOMP_MAILER_DISTRIBUTORPROFILE_BODY' );
$mailer->setSubject(JText::_( 'MYCOMP_MAILER_DISTRIBUTORPROFILE_SUBJECT' ));
$mailer->setBody($body);
$send = $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->__toString();
} else {
echo 'Mail sent';
}
}
// NOTHING TO DO IF AN UPDATE
return true;
}
return false;