I am facing a situation here.

I have a content type A with an image field(field_upload_snaps) in it. There is another content type B which also contains an image field(field_valid_snaps).

Now user will upload the pics from A content type. So if user upload 3 pics via A then 3 FID and their corresponding URIs will be created in file_managed table in Drupal 7.

Now I have a requirement where I have to insert 2 images out of 3 programatically using Drupal code. Now there is no need to generate any new image copy in public URI as images already exist via A.

I tried two approaches:-

1) I have created a new node of Type B. I tried to fetch file URI,filesize,filemime and all relevant parameter from existing fid and associate with the node using this.

 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 $node->uid = $user->uid;
 $file = (object) array(
  'uid' => $user->uid,
  'uri' => 'public://1.jpeg" ,
  'filemime' => 'image/jpeg',
  'status' => 1,

 $node->field_upload_snaps['und'][] = (array)$file;
 $node = node_submit($node); // Prepare node for a submit

But it gives me an error that "Cant insert duplicate value in file_managed". It will give because such value already exist in file_managed via A. So I am not able to save value.

2) I saved node first and then manually insert in the image field like this.

 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 $node->uid = $user->uid;
 $node = node_submit($node); // Prepare node for a submit

    'entity_type' => 'node',
    'bundle' => 'user_actualD_snaps',
    'deleted'=> 0,

But the line after node_save() doesnt execute in this case. So I am not able to save it.

Are there any functions available which will map existing images into another table?

I think the File Field sources module will solve your problem. (The D7 version works directly with the core Field module). It will, among other things, allow you to re-use files by an auto-complete textfield.

Btw: Any file appearing in file_managed can only appear once in that table, so you should not be allowed to do what you try to do in your first approach.

  • Will there be any logic references to create a new node from existing saved file. I want PHP code to do this stuff as I did it for 2 approaches. If there are any other suggestion other than going for custom module then please let me know. – simple user May 1 '13 at 20:26

File_load API solved my problem of getting the dimensions of existing file and save in another content type.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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