I have a module with a custom taxonomy term called colors. The Colors taxonomy has 1 image field where I can upload a file based on the color names. I wanted the images to be automatically installed every time my module got installed. I think that I need to add a piece of code to my module.install file under hook_install(). How do I achieve this?

  • Why the downvotes? This is a valid task. – Beau May 8 at 21:03

There are a couple of steps to doing this. For our demonstration, let's make a few assumptions:

  • The module is called image_taxonomy.
  • We have only one taxonomy term and one file to worry about.
  • The image file is called color.jpg.
  • The taxonomy term is called color_red.
  • The image field is called field_color_image.
  • The image is stored in your module's folder under /images.

Step 1. Make the file publicly available

The first challenge is to get your module-bound asset (the color.jpg file) into your site's public files as a managed file. An abbreviated version of how to do this is:

// $absolute_path_to_file is the absolute server path to /image_taxonomy/images/color.jpg
$contents = file_get_contents($absolute_path_to_file);
$file = file_save_data($contents, "public://color.jpg", FILE_EXISTS_REPLACE);
\Drupal::service('file.usage')->add($file, 'image_taxonomy', 'image', $file->id());

Now you should have a copy of your color.jpg file in your site's /files folder.

Step 2. Assign the file to the term.

// $term is a reference to the color_red taxonomy term.
  'value' => $file->id();

Last note

I would run this code from hook_modules_installed(), just to make sure that all entities and fields have been installed before attempting to assign your image file. This is highly abbreviated code, so be sure to use proper dependency injection and other best practices in your module.


| improve this answer | |
  • hello, thank you for the answer. I did what you told me to do, unfortunately I got an error : file_get_contents: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden – Deryan Thimoti May 28 at 9:58
  • @DeryanThimoti it sounds like you might need to ensure that Drupal has sufficient permissions to access that file. If the file is remote, then this answer might help you: stackoverflow.com/a/47611883/6679439 – Beau May 28 at 15:36
  • thank you Beau, in the end it worked out pretty well! You are a life saver! – Deryan Thimoti May 29 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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