1

I have a form for cloning entries. Basically it works the same way as entry add form, it saves under brand new ID, but is pre-filled with data from existing entry.

For data like text and references, this is easy. Problem starts with images. I do not want to reference one image in multiple entries, it would not be convenient for reasons that are out of scope of this question. So I wrote simple function:

function _file_copy_by_id($fid) {
  $source =  file_load($fid);
  // Copy to the same place, let the Drupal care for renaming
  $result = file_copy($source, $source->uri, FILE_EXISTS_RENAME);

  return $result->fid;
}

And in my form I made image field look like that:

'DimensionImageFile' => array(
  '#type' => 'managed_file',
  '#title' => t("Image"),
  '#title_display' => 'invisible',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(variable_get('mymodule_image_size', 5 * 1024 * 1024)),
  ),
  '#upload_location' => 'public://mymodule/image',
  '#theme' => 'preview_upload',
  '#default_value' => _file_copy_by_id($product_data['DimensionImageFile']),
),

Now, it looks OK when form is rendered:

screenshot of image field

In the database, it looks OK too. Exported entry:

INSERT INTO `file_managed`
(`fid`, `uid`, `filename`, `uri`, `filemime`, `filesize`, `status`, `timestamp`, `origname`)
VALUES
(426, 16, 'test.jpg', 'public://mymodule/image/test_3.jpg', 'image/jpeg', 37237, 1, 1391088561, 'test.jpg');

No entry in {file_usage} - just as expected.

File is there, with number added properly, but when I try to save, all I get is:

The file used in the Image field may not be referenced.


If I will add "fake" usage, like this:

function _file_copy_by_id($fid) {
  $source =  file_load($fid);
  // Copy to the same place, let the Drupal care for renaming
  $result = file_copy($source, $source->uri, FILE_EXISTS_RENAME);
  file_usage_add($result, 'mymodule', 'clone', 0, 1);
  return $result->fid;
}

form works all right. But files are reported as used. That's bad, because if user will decide to remove and replace them, cloned ones should get deleted as soon as possible, and the fact they are reported as being used prevents cleanup deletion.

3

0

Browse other questions tagged or ask your own question.