0

I have created a webform which when submitted will create a new user for my Drupal 8 site.

The user must enter his username, email, and some additional data.

I am using below code to create & validate a user:

namespace Drupal\my_module\Plugin\WebformHandler;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
// use Drupal\taxonomy\Entity\Term;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create New User Account when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Create New User Account",
 *   label = @Translation("Create New User Account"),
 *   category = @Translation("Entity Create"),
 *   description = @Translation("Create New User Account when a webform submission is submitted."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class CreateNewAccountHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

// Build Drupal DateTime & set correct format for your query.
  $current_time = \Drupal::time()->getCurrentTime();

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Username' Value.
    $username = $values['username'];

    // Get 'Password' Value.
    $password = $values['password'];    

    // Get 'Full Name' Value.
    $FullName = $values['full_name']; 

    // Get 'Phone Number' Value.
    $PhoneNumber = $values['phone_number']; 

    // Get 'Email' Value.
    $email = $values['email'];

// Create user object.
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $new_user = \Drupal\user\Entity\User::create();

    //Mandatory fields.
    $new_user->setPassword($password);
    $new_user->setEmail($email);
    $new_user->setUsername($username);    // Alphanumeric (abc, 123), space ( ), period (.), hyphen (-), apostrophe ('), underscore ( _ ), and the @ sign are only allowed.
    $new_user->set("langcode", $language);
    $new_user->set("preferred_langcode", $language);
    $new_user->set("preferred_admin_langcode", $language);
    $new_user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object.

    //Optional Fields
    $new_user->set("init", 'email');

    // Custom Fields
    $new_user->set("field_full_name", $FullName);
    $new_user->set("field_ph_nbr", $PhoneNumber);

    // Validate the user for possible errors.
    $violations = $new_user->validate();
    if (count($violations) > 0) {
      $property = $violations[0]->getPropertyPath();
      $msg      = $violations[0]->getMessage();

    // Show a custom message to user.
        \Drupal::messenger()->addError(t("$msg"));

      return FALSE;
    }

    // Activate the user Object (Status = Active).
    $new_user->activate();

    //Save user
    $new_user->save();

    // Get the new user ID.
    $new_user_id = $new_user->id();

    // Log in the user.
    user_login_finalize($new_user);

However, every time I try to create a new user using the webform, I got the below error:

This value is not a valid email address.

I have tried with:

What is wrong with my code ?

8
  • 4
    We'll need to see the code where you create the user, Ex: $new_user = User::create([ 'name' => $user_name, 'mail' => $user_mail, ]); part.
    – No Sssweat
    Commented May 25, 2020 at 2:15
  • @NoSssweat I have updated my question with full details Commented May 25, 2020 at 7:57
  • @kiamlaluno Please re-open my question as I updated it with full details. Commented May 25, 2020 at 7:59
  • I believe the problem is coming from $new_user->set("init", 'email'); Commented May 25, 2020 at 8:16
  • yes, you don't need that code as you have already set the email with setEmail
    – No Sssweat
    Commented May 25, 2020 at 8:23

1 Answer 1

1

The error message doesn't specify which field caused the validation error. In this case, the error is caused by setting the init field with a value that isn't a valid email address.

Differently from Drupal 7, in Drupal 8 the init field for the User entity is created using the email datatype. (See User::baseFieldDefinitions().)

$fields['init'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Initial email'))
  ->setDescription(t('The email address used for initial account creation.'))
  ->setDefaultValue('');

Differently from the mail field, it doesn't get further constrains. (Compare the code used to create the init field with the following code.)

$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

Still, as any entity field whose datatype is email, it has a constrain defined in the annotation of that datatype.

@DataType(
   id = "email",
   label = @Translation("Email"),
   constraints = {"Email" = {}}
)

(The classes defining that constraint are EmailConstraint and EmailValidator.)

Setting the init field for the User entity is optional, but it's generally used from administrators of a site when users claim they created an account for which they cannot retrieve the password they lost.
Depending on the purpose of the code you are using, you can either set the init field, or not. If you set it, it must set to a valid email value.

3
  • I understand that init field is optional and I would like to use it as it is important for later use; However, as mentioned in my question, using valid email address like: [email protected], [email protected], [email protected] (where "someone" is replaced by my name) does not succeeded and generated the mentioned error: This value is not a valid email address. when adding this $new_user->set("init", 'email'); to my above code. Commented Jun 20, 2020 at 9:14
  • 1
    $new_user->set("init", 'email') doesn't set init to [email protected] but to email, which indeed isn't a valid email address.
    – apaderno
    Commented Jun 20, 2020 at 9:44
  • OMG ! I can't believe I missed out such mis-typing error, it is $email instead of 'email', thank you for pointing out to it Commented Jun 20, 2020 at 10:12

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.