How do I create a user registration form where username field cannot be modified by the user and is auto-generated on the basis of two other fields in form (dynamically).

I know there are some modules available for the task in Drupal 7, but how do I achieve this in Drupal 8?

  • as there is no such module available for drupal 8. You need to create your own module.. – parth.k Jul 5 '16 at 11:30
  • as I asked in the question. How do I do that? How would I create the pattern? I have no clue where to start. – innocent rock Jul 5 '16 at 11:33
  • There is a D8 DEV (caveat emptor) version of Email Registration which would cover your query quite well. – macjules Jul 5 '16 at 15:44
  • I tried that @macjules, but it's not the solution of my problem. – innocent rock Jul 6 '16 at 10:39

This is pretty simple. Create your module, then create a form "MyRegForm" where the user can input her email and (if needed) password (twice with the '#type' => 'password_confirm'). Then, in the submit() method create your user like this:

            'name' => 'hGzfT54re39OpLLLk',
            'pass' => 'hGzfT54re39OpLLLk',
            'mail' => $data->mail,
            'status' => 1,
            'init' => $data->mail,
            'created' => time(),
            'changed' => time(),
            'login' => 0,
            'access' => 0,

The change the username and add whatever roles you need with code like

    $tuser = user_load_by_name('hGzfT54re39OpLLLk');
    $tuser->setUsername('My super name logic');
    $rc = $tuser->id();

If you don't want to create your own form for registration, go for hook_form_alter and set the #access to the "name" field to false and add a #default_value.

  • Thanks, I will try this and get back to you when I'm done :D – innocent rock Jul 6 '16 at 5:26
  • At first it showed errors but I fixed it with correcting my initial logic. Thanks @Rainer :D – innocent rock Jul 6 '16 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.