欢迎各位兄弟 发布技术文章
这里的技术是共享的
很多情况下,我们需要在对某一动作操作时候,需要自动的创建用户,如ubercart中购买产品时候,如没登陆,自动创建用户。这个是如何实现的呢?看看下面代码。
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 | //the user name of the new user $user_name = "example" ; //the users email address $email = "example@example.com" ; //set up the user fields using a random 8 character password $fields = array ( 'name' => $user_name , 'mail' => $email , 'pass' => user_password(8), 'status' => 1, ); //you can give a user roles if necessary based on the role name $fields [ 'roles' ] = array ( 'test_role' ); //the first parameter is left blank so a new user is created $account = user_save( '' , $fields ); // 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_admin_created' , $email , NULL, array ( 'account' => $account ), variable_get( 'site_mail' , 'noreply@example..com' )); |
上面代码基本实现了如何在Drupal 6中通过代码创建用户,但很多时候,用户是有用到 user profile的,就是说有一些附加的字段,那该如何做?看看下面代码:
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 44 45 46 47 | require_once './includes/bootstrap.inc' ; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); $user_name = 'my_name' ; $email = 'my_name@domain.com' ; ... $fields = array ( 'name' => $user_name , 'mail' => $email , 'pass' => $user_password , 'status' => 1, ); $account = user_save( '' , $fields ); if ( $account != NULL ) { echo "user Id: $account->uid" ; $profile_node = content_profile_load( 'bio' , $account ->uid, true); if ( $profile_node != NULL) { echo "node Id: $node_ref->nid" ; return array ( 0 => array ( 'nid' => $profile_node ->nid ), // 0 => array('USER ONE' => $user_data->field_last_name[0]['value']), ); //it's a published node, 0 if it's un published $profile_node ->status = 1; $profile_node ->title = $account ->name; //1 is promote to home page, 0 is not to promote on home page $profile_node ->promote = 0; $profile_node ->uid = $account ->uid; $profile_node ->format = 1; //filtered HTML $profile_node ->field_emp_id[0][ 'value' ] = '55555' ; $profile_node ->field_first_name[0][ 'value' ]= 'user1' ; $profile_node ->field_last_name[0][ 'value' ] = 'USER ONE' ; $profile_node ->field_title[0][ 'value' ]= 'Engineer' ; if ( $profile_node = node_submit( $profile_node )) { //saves the node node_save( $profile_node ); } else { echo " no user data found!" ; } } |