I have created content-type BookNow. In this I added field like Address, username, email, fullname..

I want to when submit booknow form than it can automatic creating new user which have own permission edit, delete the content. Thus I do like this:

function custom_booknow_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { 

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $user = \Drupal\user\Entity\User::create();    
  $user->setUsername('raam');//This username must be unique and accept only a-Z,0-9, - _ @ .
  $user->set("init", 'mail');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);

  //Save user account

  // No email verification required; log in user immediately.
  _user_mail_notify('register_no_approval_required', $user);
  drupal_set_message($this->t('Registration successful. You are now logged in.'));

But it's giving error message username unknown.

When I comment above username and email and manually put email, password, username it does not give any result.

  • Unused variables. Foremost $form_state. I also think you need to load the account before passing it to _user_mail_notify and user_login_finalize. What happens when you remove the last 4 lines. Does the error persist? – leymannx Oct 21 '19 at 10:06

Finally i have done this. It's not on node presave to create a user. It's on hook_name_entity_insert to create a user.

I have done by this code:

function hook_name_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {

$node = Node::load($entity->id());
$email = 'durge@gmail.com';

  $loaded_user = user_load_by_mail($email);

if ($loaded_user) {
  $node->uid = $loaded_user->get('uid')->value;

   function create_user($email){
   $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

   $newuser = \Drupal\user\Entity\User::create();
   $newuser->setUsername($email);//This username must be unique and accept only a-Z,0-9, - _ @ .
   $newuser->set("init", $email);
   $newuser->set("langcode", $language);
   $newuser->set("preferred_langcode", $language);
   $newuser->set("preferred_admin_langcode", $language);

    //Save user account

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.