0

I'm trying to import user data from a JSON file. So far I've managed to import user entities with some fields. The next step would be to retrieve the user ID.

The code I wrote is the following one.

$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach ($users_array as $user) {
  if(!empty($user["roles"])) {
    $values = array(
      'name' => $user["name"],
      'pass' => '',
      'status' => $user["status"],
      'mail' => $user["e_mail"],
      'field_first_name' => $user["first_name"],
      'field_last_name' => $user["last_name"],
      'field_nationality' => $user["nationality"],
      'field_introduction' => $user["introduction"],
      'field_about_me' => $user["about_me"],
      'field_current_job' => $user["current_job"],
      'field_website' => $user["website"],
    );

    $storage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $storage->create($values);
    if ($userEntity->save() == 1) {
      echo "User " . $userEntity->id . " saved!\n\n";
    }
    else {
      echo "User " . $userEntity->id . " updated!\n\n";
    }
  }
}

However, when I try to print the user ID, I get no data.

I've just started to use Drupal API, so I'm not very familiar with it. Is there something I'm doing wrong?

1 Answer 1

2

You don't have access to an id property. You need to use the id() method instead, e.g. $userEntity->id(). See the documentation for User.

For example:

echo "User " . $userEntity->id() . " saved!\n\n";
1
  • 1
    This is correct. I would add it applies to any entity whose class implements EntityInterface.
    – apaderno
    Aug 1, 2020 at 13:06

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.