2

There is an entity in which I added the Image field. The database has a custom table with different columns, including the id of the images.

Previously, I created a batch that writes data from this table to entity fields. That is, it creates many entities 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:

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();
    }
  }
nion
  • 21
  • 3

1 Answers1

0

Someting like this:

$node = $storage->load($entity_id);
$image_source_path = '/some/path'
$image_target_directory = '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);
// 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();
Balde Binos
  • 105
  • 7