drupaldrupal-7drupal-fieldsdrupal-entities

Drupal 7 | Preserve file after entity_wrapper unset?


Question is quite simple: How to preserve file on server and in file tables, so its fid is still valid after unsetting/changing value with entity wrapper?

$ewrapper = entity_metadata_wrapper('node', $sourceNode);
unset($sourceNode->field_image[$sourceNode->language][0]);
$ewrapper->save();

Now the related file is deleted as soon as the above is called. Same happends if I use:

$ewrapper->field_image->set($newImage);

In this case I need to keep the old image.

Thanks for your help guys!


Solution

  • I think that you should change file status from FILE_STATUS_TEMPORARY to FILE_STATUS_PERMANENT. Check out this answer here:

    https://api.drupal.org/comment/23493#comment-23493

    Basically, there is no file_set_status() function, like Drupal 6 had one, but now this code should do the same job:

      // First obtain a file object, for example by file_load...
      $file = file_load(10); 
    
      // Or as another example, the result of a file_save_upload...
      $file = file_save_upload('upload', array(), 'public://', FILE_EXISTS_REPLACE);
    
      // Now you can set the status
      $file->status = FILE_STATUS_PERMANENT;
    
      // And save the status.
      file_save($file);
    

    So, you load file object one or another way, change it's status property and save object back again.