10

I'm writing a script to add nodes programmatically, and I don't know the proper way to add/attach image. Actually I'm not that familiar with Drupal.

Here are the (sample) image objects I found while print_ring the existing $node I'm using:

field_image: Array ( [und] => Array ( [0] => Array ( [fxid] => 3089 [alt] => [title] => [width] => 95 [height] => 126 [uid] => 249 [filename] => helloworld.jpg [uri] => public://helloworld.jpg [filemime] => image/jpeg [filesize] => 3694 [status] => 1 [timestamp] => 1346748001 [type] => image [media_title] => Array ( ) [media_description] => Array ( ) [field_tags] => Array ( ) [field_license] => Array ( [und] => Array ( [0] => Array ( [value] => nothing ) ) ) [metatags] => Array ( ) [rdf_mapping] => Array ( ) ) ) )

The next one I found is the following.

field_temp_image: Array ( [und] => Array ( [0] => Array ( [value] => http://www.example.com/sample-path/helloworld.jpg [format] => [safe_value] => http://www.example.com/sample-path/helloworld.jpg ) ) ) `

How should I add an image to that node in that way?

0

4 Answers 4

4
+50

Let suppose your image fields in field_body_images ,

first load your node by node_load and record your image in file tables and add it to your node image field I hope this sample help you to achieve :

$n=  node_load($nid);
$file = new stdClass();      
$file->filename =$file_name;
$file->filemime =file_get_mimetype($localimagepath.$file_name);
$file->filesize = @filesize(file_create_path($localimagepath.$file_name));
$file->uid = $user->uid;
$file->status = 1;
$file->timestamp = time();
$file->list=1;
$file->data=array('alt'=>'','title'=>$n->title);
drupal_write_record('files', $file);
$record->fid=$file->fid;
$n->field_body_images[]=(array)$file;
node_save($n);
4
  • There's some code to demonstrate this in devel_generate: drupalcontrib.org/api/drupal/… Devel_generate of course generates dummy content for Drupal sites, including images. It's part of the Devel package: drupal.org/project/devel
    – paul-m
    Jan 1, 2013 at 18:31
  • Do not forget to add file_usage_add($file, 'file', 'node', $n->nid); in the end to prevent the file from accidental deletion. Dec 13, 2015 at 11:24
  • @Neograph734 it will add when node_save getting triggered.
    – Yuseferi
    Dec 13, 2015 at 13:12
  • @Neograph734 you're welcome ;). tnx for your attention
    – Yuseferi
    Dec 13, 2015 at 13:14
3

Drupal 8

For Drupal 8 it would go like following. First add the file and get a file ID. Then create the node and attach the given file ID.

$data = file_get_contents(__DIR__ . '/images/my_image.jpeg');
$file = file_save_data($data, 'public://my_image.jpeg');

$node = \Drupal\node\Entity\Node::create([
  'type'             => 'page',
  'title'            => 'Foobar',
  'field_my_image' => [
    'target_id' => $file->id(),
    'alt'       => 'Lorem ipsum',
    'title'     => 'Dolor sit amet',
  ],
]);

$node->save();
0

May be not exactly what you need, but why not just add a reference to an image in a field, like your example 2 suggests ? And then in content template file render that field as an image.

In node creation stream:

$node->field_image['und'][0]['value'] = "/path_to_image/image.jpg";

In content type:

<?php
global $base_url;
$image_source_link=$base_url . $node->field_image['und'][0]['value'];
?>
<img src="<?php print($image_source_link); ?>" />
0

In a Drupal 8 form submit callback, with entityTypeManager:

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Get values from a managed_file widget.
  $files = $form_state->getValue('uploaded_images');

  $storage_file = $this->entityTypeManager->getStorage('file');
  $storage_node = $this->entityTypeManager->getStorage('node');

  $field_image = [];
  
  foreach ($files as $fid) {
    /** @var \Drupal\file\Entity\File $file */
    $file = $storage_file->load($fid);
    // Set the file status to permanent.
    $file->setPermanent();
    $file->save();

    $field_image[] = [
      'target_id' => $file->id(),
      'alt'       => '',  
    ];
  }

  $values = [
    // Node bundle.
    'type'           => 'gallery',
    // Node title.
    'title'          => 'Gallery',
    // Node status: active.
    'status'         => 1,
    // Author ID.
    'uid'            => \Drupal::currentUser()->id(),
    // Uploaded images.
    'field_image'    => $field_image,
  ];

  /** @var \Drupal\node\Entity\Node $entity */
  $entity = $storage_node->create($values);
  $entity->save();
}

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.