I am working on a custom module (based on Model project) with a file field attached to my custom entities, now I would like to save files in certain directories according to entity id eg:


I've tried with hook_file_insert but can't get the entity id in order to use it later in file_move.

Which hook (if any) should I use? Or I am missing the whole approach?

  • Which version of Drupal? D7 or D8? – Rainer Feike Dec 12 '18 at 8:35

Assuming D8

If this is part of a "BaseFieldDefinition" of your own entity, you may set a lot of options like so:

// create photo
$fields['photo'] = BaseFieldDefinition::create('image')
    ->setDescription('Ein Photo')
        "file_directory" => 'profilbilder/[date:custom:Y]-[date:custom:m]',
        "file_extensions" => 'png gif jpg jpeg',
        "max_filesize" => '600 KB',
        "max_resolution" => '600x800',
        "min_resolution" => '30x40',
        "alt_field" => false,
        "alt_field_required" => false,
        "title_field" => false,
        "title_field_required" => false,
    ->setDisplayOptions('form', array(
        'type' => 'image_image',
        'weight' => 5,
    ->setDisplayOptions('view', array(
        'type' => 'image',
        'weight' => 1,
        'label' => 'hidden',
        'settings' => array(
            'image_style' => 'thumbnail',

As you see, you can use tags in the file_directory setting. If you craft your fields using the Drupal 8 field UI, you can also use tags in the UI field.

If it's D7, you should change to D8 :-)

  • It's still Drupal7 – rmorelli74 Dec 12 '18 at 9:10

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.