As Joomla developers, sometimes we have clients with special customization needs. I recently found myself in this situation when one client wanted a highly customized form to also register the user with Joomla at the same time as doing the form’s main function. Since usage requirements are never the same, here are the basics.
Setting Up Joomla
If this is a form that is already being loaded within Joomla, this entire section can be skipped. I like to test my scripts outside of the site environment, but as such, I need to setup the environment in order to call Joomla functions. Anyone who has done this has seen the following before:
define( '_JEXEC', 1 ); define('JPATH_BASE', dirname(__FILE__) ); define( 'DS', DIRECTORY_SEPARATOR ); /* Required Files */ require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' ); require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
While that’s a good start, we need a little more in order to be able to call the register function. First we need to load the site, and then we need to include the proper registration component and helpers.
$app = JFactory::getApplication('site'); $app->initialise(); require_once JPATH_ROOT.DS.'components'.DS.'com_users'.DS.'models'.DS.'registration.php'; require_once JPATH_ROOT.DS.'libraries'.DS.'joomla'.DS.'application'.DS.'component'.DS.'helper.php'; $model = new UsersModelRegistration(); jimport('joomla.mail.helper'); jimport('joomla.user.helper');
With all these, registration should now work.
How to Register A User
$username = 'jimporttest'; $name = 'J Port2'; $email = 'test @ mail.com'; $password = 'test'; $data = array( 'username' => $username, 'name' => $name, 'email1' => $email, 'password1' => $password, // First password field 'password2' => $password, // Confirm password field 'block' => 0 ); $return = $model->register($data);
Note that $model->register() returns the user ID on success, and false on failure. This failure is a general failure, such as passwords not matching, or username and/or email address already taken.
Logging A User In
At this point, the user is created and we can choose to log them in at the same time, assuming there is no user activation needed. To do this, all we need is the username and password:
$return = JFactory::getApplication()->login(array('username'=>$username, 'password'=>$password));