title: Programmatically change Drupal username on creation
body: <p>My Drupal site enables Single-Sign-On with an external service by sharing username and password data. If the user is new, the username and password is used to create a new account on the external service.
  The problem is the external service is not happy with spaces in the username.</p>
  
  <p>I wrote the following code into a Drupal module to remove spaces from the username when an account is being created:</p>
  
  <pre><code>function mymodule_user_insert(&amp;$edit, $account, $category){
      if( $account-&gt;is_new ){
          $name = str_replace(' ', '_', $account-&gt;name);
          drupal_set_message("CHANGING {$account-&gt;name} TO {$name}");
          $account-&gt;name = $name;
      }
  }
  </code></pre>
  
  <p>When the account is created, I see the default confirmation message such as the following:</p>
  
  <blockquote>
    <p>Created a new user account for test_test1. No e-mail has been sent.</p>
  </blockquote>
  
  <p>That confirms my string replacement is taking effect but when I view the user account it still contains spaces.</p>
  
  <p>What am I missing or doing wrong?</p>