0

I have tried to save registration data in a controller.

$values = \Drupal::request()->request->all();

     $formBuilder = \Drupal::service('entity.form_builder');
     $form = $formBuilder->getForm(User::create(array()), 'register', array());
    $formObject = new RegisterForm(\Drupal::entityManager(),
                    \Drupal::languageManager(), \Drupal::service('entity.query'));

     $form_state = (new FormState())->setValues($values);
                //$formObject->form($form,$form_state);
     $entity = $formObject->buildEntity($form,$form_state);
     $formObject->setEntity($entity);
     $formObject->form($form,$form_state);
     $formObject->submitForm($form,$form_state);
     $formObject->save($form,$form_state);

Above code produces this error:

Fatal error: __clone method called on non-object in /home/vagrant/www/drupal8/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityForm.php on line

It seems I need to inject an "entity" before buildEntity().

How did Drupal 8 manage to create a new user? Maybe the container injected that entity some where, but I am unable to find it.

2
  • Do you really want to programmatically submit a form or you just want to create new user?
    – user21641
    Jan 14, 2016 at 9:41
  • @IvanJaros, I just want to create a new user.But submit a form allows the new user to go through all default Drupal actions.
    – anru
    Jan 14, 2016 at 9:45

2 Answers 2

0

This is what I'm using for creating users. You can just use the entity_create() part.

/**
 * Creates a new user account.
 * This function makes sure the account has a unique and valid user name.
 * The only case where the account creation can fail is if the e-mail
 * address is malformed or already taken.
 *
 * @param string $mail
 *   The e-mail address of the new account.
 * @param string $name
 *   The optional login name for the new account.
 *   If no value is provided, the name is derived form the email address.
 * @param string $password
 *   The password for the new account. If empty, random password will be created.
 * @param int $status
 *   The optional status for the new account.
 * @param array $roles
 *   The optional list os user role IDs.
 *
 * @return \Drupal\user\Entity\User
 *   Returns new user object.
 * @throws \InvalidArgumentException
 *   If the email address is not valid an InvalidArgumentException is thrown.
 * @throws \Exception
 *   If new unique user could not be created an exception is thrown.
 */
function mymodule_create_user($mail, $name = NULL, $password = NULL, $status = 1, array $roles = []) {
  // Make sure we have the user name.
  // If not, use the e-mail address and remove unwanted characters.
  // If the user name is provided it will be used as is.
  if (empty($name)) {
    $name = preg_replace("\W|_", '', $mail);
  }

  // Validate the e-mail address first.
  if (!\Drupal::service('email.validator')->isValid($mail)) {
    throw new \InvalidArgumentException('Invalid e-mail address.');
  }

  // Create password if it was not provided.
  $password = $password ? $password : user_password();

  // Try 20 unique user names before giving up.
  $run = 0;
  while ($run <= 20) {
    /** @var \Drupal\user\Entity\User $user */
    $user = entity_create('user', [
      'name' => $run == 0 ? $name : ($name . $run),
      'pass' => $password,
      'mail' => $mail,
      'init' => $mail,
      'status' => $status,
      'roles' => $roles
    ]);

    // Validate the object.
    $errors = $user->validate();

    if ($errors->count() == 0) {
      $user->save();
      return $user;
    } else {
      $run++;
    }
  }

  throw new \Exception('Couldn\'t create unique user within given loop limit.');
}
1

if you just want to create new user, it is easy as you create the user object and fill it and save it:

$user = \Drupal\user\Entity\User::create();
$user->setPassword($values->getValue('pass'));
$user->enforceIsNew();
$user->setEmail($values->getValue('mail'));
$user->setUsername($values->getValue('name'));
$user->activate();
$user->save();

but in my case for example I wanted drupal to do other stuff like send welcome email...etc, so what i did, instead of last step ( $user->save() ):

$formObject = new RegisterForm($this->entityManager, $this->languageManager, $this->entityQuery);
$formObject->setEntity($user);
$formObject->save($form,$form_state); // $form and $form_state can be created like you did.
// if you want to get the newly created user
$user = $formObject->getEntity();

on the other hand I have tried to get your code working, and the following was the outcome code:

$formObject = $this->entityManager->getFormObject('user','register');
$formObject->setEntity($user);
$formStateObject = (new FormState())->setFormObject($formObject);
$form = [];
$form = $formObject->buildForm($form,$formStateObject);
$formObject->validateForm($form,$formStateObject);
$formObject->submitForm($form,$formStateObject);
$formObject->save($form,$formStateObject);

Hope that helps.

Your Answer

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

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