0

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?

4
  • as there is no such module available for drupal 8. You need to create your own module..
    – parth.k
    Commented Jul 5, 2016 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. Commented Jul 5, 2016 at 11:33
  • There is a D8 DEV (caveat emptor) version of Email Registration which would cover your query quite well.
    – macjules
    Commented Jul 5, 2016 at 15:44
  • I tried that @macjules, but it's not the solution of my problem. Commented Jul 6, 2016 at 10:39

1 Answer 1

1

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:

\Drupal\user\Entity\User::create([
            'name' => 'hGzfT54re39OpLLLk',
            'pass' => 'hGzfT54re39OpLLLk',
            'mail' => $data->mail,
            'status' => 1,
            'init' => $data->mail,
            'created' => time(),
            'changed' => time(),
            'login' => 0,
            'access' => 0,
        ])->save();

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');
    $tuser->addRole("whatever");
    $tuser->save();
    $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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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