在创建时以编程方式更改 Drupal 用户名

Programmatically change Drupal username on creation

我的 Drupal 站点通过共享用户名和密码数据启用与外部服务的单点登录。如果用户是新用户,则用户名和密码用于在外部服务上创建新帐户。 问题是外部服务对用户名中的空格不满意。

我将以下代码写入 Drupal 模块以在创建帐户时从用户名中删除空格:

function mymodule_user_insert(&$edit, $account, $category){
    if( $account->is_new ){
        $name = str_replace(' ', '_', $account->name);
        drupal_set_message("CHANGING {$account->name} TO {$name}");
        $account->name = $name;
    }
}

创建帐户后,我看到如下默认确认消息:

Created a new user account for test_test1. No e-mail has been sent.

这确认我的字符串替换正在生效,但是当我查看用户帐户时它仍然包含空格。

我错过了什么或做错了什么?

我使用了 hook_user_presave() 来让它工作。参考这个:user hooks。到时候,hook_user_insert()调用用户已经创建。

我使用了hook_user_presave(),因为它会在即将创建或更新用户帐户时调用。我使用 $account->is_new 仅对新帐户执行任务。然后我直接编辑 $edit 而不是 $account 因为 user_save() 需要第二个参数(数组)保存在 $account.

function mymodule_user_presave(&$edit, $account, $category) {
  if( isset($account->is_new) && $account->is_new === TRUE ) {
    $name = str_replace(' ', '_', $edit['name']);
    // Also consider trimming the length and to lowercase your username.
    drupal_set_message("CHANGING {$edit['name']} TO {$name}");
    $edit['name'] = $name;
  }
}