Drupal 7 开发内部培训资料, 分头诗人

Drupal 7 通过代码创建用户?

猪跑啦独家原创专稿,欢迎您转载本文,转载请注明来源。

Drupal 6请移步到 Drupal 6  通过代码创建用户?

很多情况下,我们需要在对某一动作操作时候,需要自动的创建用户,如ubercart中购买产品时候,如没登陆,自动创建用户。这个是如何实现的呢?Drupal 6中的做法,在Drupal 7中会有所改变,看看下面代码。

//This will generate a random password, you could set your own here
  $password = user_password(8);
 
  //set up the user fields
  $fields = array(
    'name' => 'user_name',
    'mail' => 'user_name@example.com',
    'pass' => $password,
    'status' => 1,
    'init' => 'email address',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    ),
  );
 
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);
 
  // If you want to send the welcome email, use the following code
 
  // Manually set the password so it appears in the e-mail.
  $account->password = $fields['pass'];
 
  // Send the e-mail through the user module.
  drupal_mail('user', 'register_no_approval_required', $email, NULL, array('account' => $account), variable_get('site_mail', 'noreply@example..com'));

注:你可以附加角色进去,通过role id

上面代码基本实现了如何在Drupal 7中通过代码创建用户,但很多时候,用户是有一些附加的字段,那该如何做?Drupal 7附加字段的方式是需要entity的,这点跟drupal 6有所区别,看看下面代码:

 

$new_user = array(
		'name' => 'Username',
		'pass' => 'Password',
		'mail' => 'Email',
		'signature_format' => 'full_html',
		'status' => 1,
		'timezone' => 'America/New_York',
		'init' => 'Email',
		'roles' => 'Roles',
		'field_first_name' =>
			array(LANGUAGE_NONE =>
			array(0 =>
			array('value' => 'First Name'))),
		'field_last_name' =>
			array(LANGUAGE_NONE =>
			array(0 =>
			array('value' => 'Last Name'))),
);
$account= user_save(NULL, $new_user);
 
db_insert('field_data_field_first_name')
	->fields(array(
	'entity_type' => 'user',
	'bundle' => 'user',
	'deleted' => 0,
	'entity_id' => $account->uid,
	'language' => 'und',
	'delta' => 0,
	'field_first_name_value' => 'First Name',
	))
	->execute();
 
db_insert('field_data_field_last_name')
	->fields(array(
	'entity_type' => 'user',
	'bundle' => 'user',
	'deleted' => 0,
	'entity_id' => $account->uid,
	'language' => 'und',
	'delta' => 0,
	'field_last_name_value' => 'Last Name',
	))
	->execute();