Domanda

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?

È stato utile?

Soluzione

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";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a drupal.stackexchange
scroll top