0
  $article = entity_create('node', array(
    'type' => 'article',
    'title' => generate_demo_content('lorem_ipsum_title'),
    'body' => array(
      'value' => generate_an_article(),
      'format' => 'full_html',
    ),
    // how attach here, a file or an image?
  ));
  $article->save();

I create an article from a .module file, and I would like know if I can link an image/file object to my article?

By example if I have an image inside /modules/my_module_name/images/img.jpg, how I can insert this image inside my article object from my .module file please?

Thanks.

1 Answer 1

0

I have tried the below code with node_save method but not with entity_create way. Check if it works.

$dir = 'public://';
if (file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
  $file = file_save_upload('image', array(), $dir, FILE_EXISTS_RENAME);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $attachment = array(
    'fid' => $file->fid,
    'display' => 1,
    'description' => $file->name,
    'title' => $values->tooltip
  );
}

$article = entity_create('node', array(
  'type' => 'article',
  'title' => generate_demo_content('lorem_ipsum_title'),
  'body' => array(
    'value' => generate_an_article(),
    'format' => 'full_html',
  ),
  'field_attachment' => $attachment, //may need to change here
));

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.