Getting selected (audio) file from files field

So my scenario is: have Files field in Panel with multiple audio files uplaoded, but only one is selected. I have multiple languages, so when switching language, then selected file changes.

Problem starts, that I can not get that selected file. For example $audio->first() or $audio->current() returns first file in that list, but its not the selected.

My code:

$audio = $page->audio();
$audioFile = $audio->first(); // this returns first file... need to get selected file.

p.s. previously had dirty workaround where in foreach loop checking page content:

files: "- my_audio.mp3"

and compare this name with current iteration filename, but this is so dirty. And this stoped to work with Kirby v4, where file link is stored (because cannot compare with filename):

files: "- file://TmEHDWEOUSu1AJrN"

So there are first(), last() and current(), but no selected() - this would be super convenient.

btw whats the difference between first() and current() - they both return first file in the list, which is not selected.

The problem is your field name, because it clashes with $page->files();

So you would have to go via content:

$files = $page->content()->get('files')->toFiles();
1 Like

Thank You @texnixe
Just one tiny additional thing - as I was dealing with multilanguage it was necessary to pass $lng code to content() function. And I was converting it to single file:

$file = $page->content($lng)->get('files')->toFile();