2

I have a content type to which I added an image field. The database has a custom table with different columns, including the image ID.

Previously, I created a batch that writes data from this table to entity fields. It creates many nodes from the records in the table with filled fields. I need to do the same but for images. Part of the code from the batch is the following one.

if (empty($entity_id)) {
  $info = [
    'type' => 'product',
    'title' => $productTitle,
    'field_name' => (string) $product->name,
    'field_product_cid' => (string) $product->cid,
    'field_custom_url' => $product->url,
    'uid' => 1,
    // here I need to add an image to the field_image field from the table
  ];
  $node = $this->entityTypeManager->getStorage('node')->create($info);
  $node->save();
}
else {
  $storage = $this->entityTypeManager->getStorage('node');
  $node = $storage->load($entity_id);

  // Change fields of node.
  $node->set('title', $productTitle);
  $node->set('field_name', (string) $product->name);
  $node->set('field_custom_url', $product->url);
  // and here change field_image if the node already exists
  $node->save();
}

1 Answer 1

2

Someting like this:

$node = $storage->load($entity_id);
$image_source_path = '/some/path'
$image_target_path = 'public://some/path';
$image_data = file_get_contents ($image_source_path);
$image_alt = 'some alt text';
// Drupal 9 >= 9.3.0 or Drupal 10
$image_object = \Drupal::service('file.repository')
                    ->writeData($image_data, $image_target_path);
// Drupal 8
//$image_object = file_save_data ($image_data, $image_target);
$node->set('field_image', [
    'target_id' => $image_object->id(),
    'alt' => $image_alt,
]);
$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.