Automatically Prepend Files to the Top of a Files Field List

Hello,

I am working on a project and encountered a challenge with the Files field in my blueprint. I’m looking to implement functionality similar to the “prepend” option available in the Structure field, but for the Files field. Specifically, I want new files added to a specific Files field (imagesindex) to automatically appear at the top of the list in the panel, instead of being added to the bottom.

Here is the blueprint configuration for the imagesindex field:

imagesindex:
  label: Images/Videos
  type: files
  uploads: filesindex
  layout: cards
  size: tiny
  sortBy: filename desc
  text: "{{ file.structureText.isEmpty ? file.filename : file.structureText.toStructure.first.text }}"
  image:
    ratio: 1/1
    back: "#595959"
  info: "{{ file.niceSize }}"

I’ve attempted to use a file.create:after hook to change the sort order of newly uploaded files, but it hasn’t worked as expected. My goal is for any file uploaded or chosen for this field to automatically be placed at the top of the list in the panel.

Here is an example of the hook I’ve tried:

'hooks' => [
    'file.create:after' => function ($file) {
        $file->changeSort(1)
    }
],

However, this approach does not seem to affect the order of files in the panel. I’m looking for insights or suggestions on how to achieve this functionality. Is there a way to make the Files field behave like the Structure field with the “prepend” option, or is there a workaround that I could implement?

Any advice or guidance would be greatly appreciated!

Thank you in advance for your help!

Ok, first issue is that you are sorting your files by filename, so any sort order you apply to uploaded files doesn’t have any effect on your files field.

Secondly, when you select a file (instead of upload it), the hook will not kick in.

Having said that, the sorting number of the files and the order in a files field are two different things, after all, the files will be stored in the content in the order in which they are selected.

Thank you for your insights. Following your advice, I’ve removed the sortBy from my file field. However, this doesn’t seem to resolve my issue.

Is it possible to achieve what I’m aiming for with a hook that aim both upload or selected file ?

Thanks again for your assistance.

Right, because there is no sortBy property for a files field.

So what you would need to do:

  1. When you upload a file, you could use a file.create:after hook to attach a sort order to the file. As an alternative, you could use a date field (with time enabled) in the file blueprint with a default set to now (no hook required, so IMO the better option). Both options will not work for already uploaded files.

  2. Whenever the page is updated, check if the value of the imagesindex field has changed and if so, reorder the files according to their number or date and update the page.