/**
 * Date dd/mm/yyyy
 * Creates a user with profile values.
 *
 * @param $data
 *   $_POST data for example.
 *
 * @return
 *   $user Object.
 */
function my_module_create_user($data) {
	// Drupal User module function that generates MD5 hash password
	$pass = user_password();
	$newuser = array(
	  'name' => $data['name'],
	  'mail' => $data['mail'],
	  'status' => 1, // Sets user as Active
	  'pass' => $pass
	);
	$auto_user = user_save('', $newuser);
	$rid = 4; // Assign Role ID
	$uid = $auto_user->uid;
	db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $uid, $rid);
    // Populates profile values
	$profile = array(
	  'firstname' => $data['firstname'],
	  'lastname' => $data['lastname'],
	  'company' => $data['company'],
	  'address' => $data['address'],
	  'city' => $data['city'],
	  'state' => $data['state'],
	  'country' => $data['country'],
	  'phone' => $data['phone'],
	 );
	 // Adds details under Personal Information Category set in Profile
	 profile_save_profile($profile, $auto_user, 'Personal Information'); 
	 // Load the new user Object
	 $account = user_load(array('uid' => $auto_user->uid, 'status' => 1));
	 global $user;
	 $user = $account;
	 drupal_set_message(t('You have been authenticated'));
	 db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $user->uid);
	 sess_regenerate();
	 // Finally send an Email
	 /*
	 * Mail templates available:
	 * register_no_approval_required
	 * register_admin_created
	 * register_pending_approval - Need to set Status above as 0 if this option is required
	 */
	 drupal_mail('user', 'register_no_approval_required', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
          // Set the redirection to where you want
	 drupal_goto('home');
}

Comments

cfaust’s picture

This is useful, thanks for it.

I'm curious about doing the roles separately - is there a reason why you didn't do it as part of user_save? I'm about take this same approach on our site.

jayboodhun’s picture

I had a few issues with this but then figured out it can be done this way for the roles:

add inside $newuser array:

$roles => array('authenticated user', 'some other role'),

Cheers
Jay

sergh27’s picture

any ideas are welcome
create preview form and create profile when the form is submitted
http://drupal.org/node/759588