I'm looking to add some additional functionality to the user registration process. Basically, we will be creating "access codes" that can be used N number of times during registration. Once N users have signed up using that code, the plugin that I'm writing will prevent additional users from registering on the site.
Right now, I'm having trouble determining how to add errors to the users.onBeforeSaveUser
event. My plugin checks availability of the access code that was submitted during the registration process, and I'd like to prevent Craft from saving the user if the code isn't valid/enabled. Here's what the code looks like:
<?php
namespace Craft;
class GatekeeperPlugin extends BasePlugin
{
...
function init()
{
craft()->on('users.onBeforeSaveUser', function(Event $event) {
// The user that's about to be saved
$user = $event->params['user'];
// Determine if an access code was submitted
$accessCodeUsed = isset($user->contentFromPost['accessCodeUsed']) ? $user->contentFromPost['accessCodeUsed'] : false ;
// If there was an access code submitted...
if ($accessCodeUsed)
{
// Look for it in the database
$queryAccessCode = craft()->db->createCommand()
->select('id, field_code, field_limit, field_timesUsed')
->from('content')
->where(array('field_code' => $accessCodeUsed))
->limit('1')
->queryRow();
// If the code was found...
if($queryAccessCode)
{
...Do some stuff
}
// If the code wasn't found...
else
{
// Prevent Craft from saving the user
// Add error "Sorry, that code is not valid."
}
}
});
}
}
It appears that error messages can only be added to models, but I'm working with an event here. The event has a user model within it, but trying to add errors to it (e.g. $event->params['user']->addErrors([array of errors])
) hasn't worked for me. Any pointers, here?