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

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

$user = \Drupal\user\Entity\User::create();
$user->set("init", 'test@test.com');
$user->set("langcode", $language);
$user->set("preferred_langcode", $language);
$user->set("preferred_admin_langcode", $language);

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?

  • 1
    I'd try to tackle this down systematically. Simply start by creating a bare user, can you create the user? Then try to remove or add lines of your code back until it works.
    – leymannx
    Jun 10, 2020 at 12:14
  • I try by many ways but unable to create user Jun 11, 2020 at 5:43

1 Answer 1


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->fields to speed-up further look-ups and to keep track of
// fields objects, possibly holding changes to field values.
if (!isset($this->fields[$name][$langcode])) {
  $definition = $this->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.

  • Hi @kiamlaluno thanks for reply , even I try by code you shared it is showing same error , do I need to disable any module , much appreciated your reply Jun 11, 2020 at 5:40
  • You will get that error until you don't find which module is causing the error, and you uninstall it. That is something you need to do by debugging your site. There isn't any way to know which module is causing the error, from the exception output.
    – apaderno
    Jun 11, 2020 at 8:58

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.