I'm trying to import user profile pictures from Drupal 7 to Drupal 8. So far I've managed to upload the picture from the url and save it to the file system, create Media entity and use the user id as author. However, the picture doesn't show to the user profile (Manage Form Display), neither to the Edit Media Content Type page.
Here is the code I have so far:
$values = array(
'name' => $user["name"],
'pass' => [
'value' => $user["pass"],
'pre_hashed' => TRUE,
],
'status' => $user["status"],
'mail' => $user["mail"],
'field_first_name' => $user["field_first_name"],
'field_last_name' => $user["field_last_name"],
);
$userStorage = \Drupal::entityTypeManager()->getStorage('user');
$userEntity = $userStorage->create($values);
$replaced = str_replace("\\", "", $user["picture"]);
$imageData = file_get_contents($replaced);
$fileName = basename($replaced);
$file = file_save_data(
$imageData,
"public://". $fileName,
FileSystemInterface::EXISTS_RENAME
);
$media = Media::create([
'bundle' => 'image',
'uid' => $userEntity->id(),
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'field_media_file' => [
'target_id' => $file->id(),
'alt' => $file->getFilename(),
],
'thumbnail' => [
'target_id' => $file->id(),
'alt' => $file->getFilename(),
],
]);
$media->setName($fileName)->setPublished(TRUE)->save();
$userEntity->field_user_picture->appendItem($media);
Is the something missing in the code?
UPDATE
I noticed (as also pointed out in the comments) $userEntity->save();
is missing after $userEntity->field_user_picture->appendItem($media);
.
However, after I added that line, I get the following error:
Error: Call to undefined method Drupal\media\Entity\Media::getFileUri() in Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (line 321 of /var/www/html/web/core/modules/image/src/Plugin/Field/FieldType/ImageItem.php) #0 /var/www/html/web/core/lib/Drupal/Core/Field/FieldItemList.php(233): Drupal\image\Plugin\Field\FieldType\ImageItem->preSave()
Is it related to file_save_data()
function?
appendItem
looks valid, the coreFileUpload
class uses the same method to append a file entity$userEntity->save();
was missing.