I have a a php function that works for creating a new user in Joomla 2.5. This function is used to synchronize an external customer database with Joomla.
The new requirement is that the email address needs to be an optional field. I can't seem to get the JFactory function to work without an email address. Is there another way to get the user created?
function add_joomla_user($username, $email, $name, $password, $group) {
// Creates a new user in Joomla database with passed in information
$return_message = '';
$mainframe =& JFactory::getApplication("site");
$mainframe->initialise();
$user = JFactory::getUser(0); // it's important to set the "0" otherwise your admin user information will be loaded
jimport('joomla.application.component.helper'); // include libraries/application/component/helper.php
$usersParams = &JComponentHelper::getParams( 'com_users' ); // load the Params
$userdata = array(); // place user data in an array for storing.
$userdata['username'] = $username;
$userdata['email'] = $email;
$userdata['name'] = $name;
$userdata['password'] = $password;
$userdata['password2'] = $password;
$defaultUserGroup = $usersParams->get('new_usertype', $group);
$userdata['groups']=array($defaultUserGroup);
$userdata['block'] = 0; // set this to 0 so the user will be added immediately.
if (!$user->bind($userdata)) { // bind the data and if it fails raise an error
JError::raiseWarning('', JText::_( $user->getError())); // something went wrong!!
$return_message = 'Error binding data: ' . $user->getError();
}
if (!$user->save()) {
JError::raiseWarning('', JText::_( $user->getError()));
$return_message = 'Error creating user: ' . $user->getError();
} else {
$return_message = 'Created user';
}
return $return_message;
}