欢迎各位兄弟 发布技术文章
这里的技术是共享的
很多情况下,我们需要在对某一动作操作时候,需要自动的创建用户,如ubercart中购买产品时候,如没登陆,自动创建用户。这个是如何实现的呢?Drupal 6中的做法,在Drupal 7中会有所改变,看看下面代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | //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有所区别,看看下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | $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(); |