Exporting default image of field

Public

</> CopyGet raw version
php
  1. /**
  2.  * Create the image field's default file reference.
  3.  *
  4.  * @see http://kybest.hu/en/blog/exporting-image-field-defaults-in-d7
  5.  *
  6.  * @param $filename
  7.  * Filename to upload.
  8.  * @param string $source_dir
  9.  * Directory of uploaded file without leading slash.
  10.  *
  11.  * @return int
  12.  * File object.
  13.  */
  14. function drupal_upload_default_image($filename, $source_dir) {
  15. $source_uri = "$source_dir/$filename";
  16. $destination_uri = "public://$filename";
  17.  
  18. $file = (object) array(
  19. 'uid' => 1,
  20. 'filename' => $filename,
  21. 'uri' => $source_uri,
  22. 'filemime' => file_get_mimetype($source_uri),
  23. 'filesize' => filesize($source_uri),
  24. 'status' => FILE_STATUS_PERMANENT,
  25. );
  26. if ($file = file_copy($file, $destination_uri, FILE_EXISTS_REPLACE)) {
  27. return $file;
  28. }
  29. return NULL;
  30. }
  31.  
  32. /**
  33.  * Upload default image.
  34.  */
  35. function MYMODULE_update_7001() {
  36. if ($file = drupal_upload_default_image('default-image.jpg'), 'path/to/file') {
  37. variable_set('MYMODULE_default_image_fid', $file->fid);
  38. }
  39. else {
  40. throw new UpdaterException('Could not upload default image!');
  41. }
  42. }
  43.  
  44. /**
  45.  * Implements hook_field_default_field_instances_alter().
  46.  */
  47. function MYMODULE_field_default_field_instances_alter(&$fields) {
  48. if (isset($fields['node-MY_NODE_TYPE-field_image']['settings']['default_image'])) {
  49. $fid = $fields['node-MY_NODE_TYPE-field_image']['settings']['default_image'];
  50. $fields['node-MY_NODE_TYPE-field_image']['settings']['default_image'] = variable_get('MYMODULE_default_image_fid', $fid);
  51. }
  52. }