Image file field correct way

panelfield

#1

Hello, everyone, great to be here.

Having some doubts about the correct way to deal with File Field, restricted to images.

  1. In my header snippet, I did this
<?php if($image = $site->favicon()->isNotEmpty()): ?>
      <link rel="apple-touch-icon" sizes="180x180" href="<?= $site->favicon()->toFile()->crop(180)->url() ?>">
      <link rel="icon" type="image/png" href="<?= $site->favicon()->toFile()->crop(32)->url() ?>" sizes="32x32">
      <link rel="icon" type="image/png" href="<?= $site->favicon()->toFile()->crop(16)->url() ?>" sizes="16x16">
      <meta name="msapplication-TileImage" content="<?= $site->favicon()->toFile()->crop(150)->url() ?>" />
      <?php endif ?>

Is that the right/best way to do it?

  1. In my site.yml I made this
favicon:
                label: Favicon
                type:  files
                help: Must be PNG file, square, max 512px height. 
                accept:
                  mime: image/png
                  maxheight: 512
                multiple: false

The goal was to restrict file type to .png but it for sure doesn’t work. I am missing some logic with this.

Please help :slight_smile:


#2

There is no accept option for the files field. But you can use a query to limit the files shown to images.

 query: page.images

Or if you want to limit to png_

 query: page.images.filterBy('extension', 'png');

As regards the header, it’s not a good idea to call crop without checking for the image first.

I suggest the following:

<?php if($image = $site->favicon()->toFile()): ?>
      <link rel="apple-touch-icon" sizes="180x180" href="<?= $file->crop(180)->url() ?>">
      <link rel="icon" type="image/png" href="<?= $file->crop(32)->url() ?>" sizes="32x32">
      <link rel="icon" type="image/png" href="<?= $file->crop(16)->url() ?>" sizes="16x16">
      <meta name="msapplication-TileImage" content="<?= $file->crop(150)->url() ?>" />
<?php endif ?>

#3

Regarding the snippet, you can check if the field has a valid reference to file in the if statement and then just use the variable you are assigning it to:

<?php if($image = $site->favicon()->toFile()): ?>
    <link rel="apple-touch-icon" sizes="180x180" href="<?= $image->crop(180)->url() ?>">
    <link rel="icon" type="image/png" href="<?= $image->crop(32)->url() ?>" sizes="32x32">
    <link rel="icon" type="image/png" href="<?= $image->crop(16)->url() ?>" sizes="16x16">
    <meta name="msapplication-TileImage" content="<?= $image->crop(150)->url() ?>" />
<?php endif ?>

#4

#5

Thank you very much.
That’s just what I was looking for. :slight_smile:


#6

Thank you, you are right.


#7

Oh, and welcome to the forum, of course :slightly_smiling_face:


#8

Just one note, for someone reading this

In site options is

query: site.images