Weird url() format from Files field

Hi there, I must be overlooking something super simple, but I’m getting strange results from a url(). I’m pulling from a field on a subpage called filesPDF like this:

<a href="<?= $subpage->filesPDF()->first()->url(); ?>" target="_blank">

and the result I’m getting is:

<a href="- name.pdf" target="_blank">

sometimes I also get the same thing but with -> in it and lots of %20%20. I’ve re-read the href a hundred times over and there are no extra spaces or anything, so really unsure why the “-” and sometimes “->” are finding their way into the link. Any ideas? All help appreciated!

A files field stored the file id and if you cann $subpage->filesPDF() what you get is a field object, no a file or files object.

You first have to convert your field value to a file objects using toFile() or a files object using toFiles() if you store multiple files in your field:

<?php if ( $file =  $subpage->filesPDF()->toFile() ) : ?>
    <a href="<?= $file->url(); ?>" target="_blank">
<?php endif ?>
<?php foreach ( $subpage->filesPDF()->toFiles() as $file ) : ?>
    <a href="<?= $file->url(); ?>" target="_blank">
<?php endforeach; ?>
1 Like