I have a simple task: one particular front-end form on a website is being used to update a logged in user's profile. It works. It uses the users.onSaveUser
action.
I need to fire off notification emails when a particular input value is true on form submission.
My first attempt was a plugin that just watched the onSaveUser
event; but while I could get that to send email, I could not seem to get access to the form fields in order to check whether the email should be sent or not. Therefore it sent emails whenever a user was saved, including when edited in the back-end.
Now I'm trying a plugin that has its own action - myPlugin/saveUser
. But I am essentially duplicating the code in the existing users/saveUser function... and that makes it brittle. Is there not a way to get this done by just testing a field property and then passing everything over to the built-in users/saveUser action?
How would you do this?
Here's the simple plugin I had, which couldn't get the POST data and was therefor no good...
public function init() {
craft()->on('users.saveUser', function(Event $event) {
$this->requirePostRequest();
// is in the relevant user group?
if($event->params['user']->isInGroup('applications')){
// check this is a submission from the front end form
$applicationFormFrontend = craft()->request->getPost('applicationFormFrontend', 'default');
// check the Consent field was true on this submission
$consentGiven = craft()->request->getPost('fields[consentGiven]', 'default');
NotifyPlugin::log("The value of applicationFormFrontend is $applicationFormFrontend.", LogLevel::Info);
NotifyPlugin::log("The value of consentGiven is $consentGiven.", LogLevel::Info);
if($applicationFormFrontend == '1' and $consentGiven == '1') {
// Write Email
...
// send the mail
craft()->email->sendEmail($notificationEmail);
}
}
});
}
EDIT, SOLUTION:
The reason I was not getting values for
$consentGiven = craft()->request->getPost('fields[consentGiven]', 'default');
is because it's the wrong style. It's why it was always getting 'default'. The fix is to use dot notation:
$consentGiven = craft()->request->getPost('fields.consentGiven', 'default');
The original code (as above) works with this modification.
$this->requirePostRequest();
that's only used in controller actions. This event gets triggered by a user save and won't know if that came from the CP or the front end.