10 February 2015

Since this snippet includes a lot of information the title is simply a bunch of keywords. Basically we are using file uri to determine if it exists and is managed or needs to be saved as new managed file. Then use "entity_metadata_wrapper" to save the field to entity. This example is from migration of files from another Drupal installation.

Source code viewer
  1. $uri = preg_replace('/public:\/\/(.*?)/', 'public://old_files/$1', $uri);
  2. $uri = file_stream_wrapper_uri_normalize($uri);
  3.  
  4. if (file_exists($uri)) {
  5. if ($files = entity_load('file', FALSE, array('uri' => $uri))) {
  6. $file = !empty($files) ? reset($files) : FALSE;
  7. }
  8. else {
  9. $file = new StdClass();
  10. $file->uri = $uri;
  11. $file->uid = 0;
  12. $file->filename = basename($uri);
  13. $file->filemime = file_get_mimetype($uri);
  14. $file->status = FILE_STATUS_PERMANENT;
  15. $file = file_save($file);
  16. }
  17.  
  18. $wrapper = entity_metadata_wrapper('node', $node);
  19. $wrapper->field_event_image->set(array('fid' => $file->fid));
  20. }
Programming Language: PHP