Unable to programmatically create user I am trying to programmatically create a user in Drupal 8 using the following code.

$language = \Drupal::languageManager()-&gt;getCurrentLanguage()-&gt;getId();

$user = \Drupal\user\Entity\User::create();
$user-&gt;setPassword($form_state-&gt;getValue('pass'));
$user-&gt;enforceIsNew();
$user-&gt;setEmail('test@test.com');
$user-&gt;setUsername('test_test');
$user-&gt;set("init", 'test@test.com');
$user-&gt;set("langcode", $language);
$user-&gt;set("preferred_langcode", $language);
$user-&gt;set("preferred_admin_langcode", $language);
$user-&gt;activate();
$user-&gt;save();


When I execute it, I get the following exceptions.


  Drupal\Core\Entity\EntityStorageException: Field type is unknown. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 783 of  /home/printhouseheroes/public_html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
  InvalidArgumentException: Field type is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 586 of
  /home/printhouseheroes/public_html/core/lib/Drupal/Core/Entity/ContentEntityBase.php).


How can I avoid getting those exceptions?
The exceptions aren't caused from the code shown in the question. The second exception is caused from the following code in ContentEntityBase::getTranslatedField().

// Populate $this-&gt;fields to speed-up further look-ups and to keep track of
// fields objects, possibly holding changes to field values.
if (!isset($this-&gt;fields[$name][$langcode])) {
  $definition = $this-&gt;getFieldDefinition($name);
  if (!$definition) {
    throw new \InvalidArgumentException("Field $name is unknown."); // Line 586.
  }

  // Omissis.

}


There is a module that is trying to access the type field, which doesn't exist for the User entity.

Your code is correct. Eventually, instead of setting the user fields using a setter method, you could use the array User::create() accepts as first parameter, which uses the following array keys (among others):


name
mail
pass
status
roles (an array)
langcode
preferred_langcode
preferred_admin_langcode


There isn't an equivalent value for enforceIsNew(), so you need to call that method on the created user object.