Conditional fields depending on file type

Hello again,

I am trying to set up a file blueprint that works both for images and videos (as you can only assign one type of template in a section, correct?). Now, as the metadata I require for each are slightly different, I would like to show some fields/sections only conditionally depending on the file being an image or video.

Is there any way to do this? What would the syntax look like?

Thank you!

I don’t think you can trigger the conditional stuff based on file type. you could put tabs in the meta and put the video stuff in one tab and image fields in the other.

Personally i just use two sections, and set the template on each respectively. I leave the video one in list mode so it doesn’t take much room, and set the images one to cards. I normally put these under a "Media’ tab in the main page blueprint.

alternatively you could put a toggle field in the meta for toggling between video and image, and trigger the fields the way.

thirdly, you could use an upload hook to set the desired template in the files meta based on the file type. Its a bit of a cheat but should work.

This should do it in the config

'hooks' => [
  'file.create:after' => function ($file) {
      if (strpos($file->filename(), '.mp4') !== false) {
			 'template' => 'YOUR TEMPLATE NAME',

Set the images meta template on the section, and the above code should reset it if the uploaded file happens to be a an MP4 video.

Why do you always use strpos() instead of checking the file extension?

if($file->extension() === 'jpg') {
  // do stuff

In the current case I’d probably use $file->type()

Instead of using different templates, you could also store the file type via a hook in a field and then show fields depending on that value.

1 Like

Well… because i did not know there was a thing for that :slight_smile: I just yoinked what I did in my Gilmour MP3 plugin… i can go and clean that up a little now…


Normally I google for how to find something in a string and it comes back with strpos()… i forget to check if Kirby has a helper.

BTW: There are already two ideas issues that would help solve your use case and which you therefore might want to upvote (especially the first one)

Thank you, that’s what I ended up doing now.
Here’s the code for the hook, in case anyone needs something similar in the future:

  'hooks' => [
    'file.create:after' => function ($file) {
      $file->update(['filetype' => $file->type()]);

And then, to show my section only if it’s an image:

    type: fields
      filetype: image
1 Like