Srcset toFile() url() from structur field snippet

#1

Hello,

I trie to use the srcset in a snippet, but I dont know how to get the right url() toFile() from a structur field.

Template

      <?php 
      $counter = 0;
      $gallery_id = "gallery-".$counter;
      snippet('lightbox',
      array('structur_field_name' => 'gallery',
      'collection' => $page ,
      'gallery_name_unique' => $gallery_id
      ))
      ?>

Snippet

$image_collection = $collection->{$structur_field}()->toStructure();
  $structurfield_count = $collection->{$structur_field}()->toStructure()->count();


    foreach($image_collection as $single_image): ?>

   

    <?php
    
       
    //old version
    //$image = $single_image->gallery_img()->toFile();
    //$thumbURL = $image? $image->resize(2000)->url(): '';
    //$thumbURL_mobile = $image? $image->resize(1200)->url(): '';



        $image2 = $single_image->gallery_img()->toFile();
        $thumb = $image? $image->resize(2000)->url(): '';
       




    ?>

      <img
          src="<?= $thumb ?>"
          srcset="<?= $image2->srcset([300, 800, 1024]) ?>" />

error output: Call to a member function srcset() on null

What I do wrong ?

greetings john

0 Likes

#2

You define a variable $structure_field_name here, but then in the snippet you use

$image_collection = $collection->{$structur_field}()->toStructure();

??

Also, never call any methods without checking for the object first. In your code above, you don’t know if $image2 is a file or not.

0 Likes

#3

I have corrected the var name error, but still the same error output.

When I test the output without srcset

$image2 = $single_image->gallery_img()->toFile();
$thumb = $image2? $image2->resize(2000)->url(): '';
 
  echo $image2;

<img alt="" src="https://xxxxxx.com/media/pages/fotosammlung/3882932676-1553528989/foto0097.jpg">

It is right ?

0 Likes

#4

As I said above, hat whole code bit should be wrapped in an if statement:

<?php if($image2 = $single_image->gallery_img()->toFile()): ?>
<?php $thumb = $image2? $image2->resize(2000)->url(): ''; ?>
<img
          src="<?= $thumb ?>"
          srcset="<?= $image2->srcset([300, 800, 1024]) ?>" />
<?php endif ?>

(I think I need some boilerplate text for this as I keep repeating myself :wink:)

0 Likes

#5

Okay thank you, now it works. :smiley:

Call to a member function srcset() on null
Does that mean a image field gallery_img() in the structure field is empty ?

0 Likes

#6

Yes, either an empty field or the file was deleted after having been stored. That’s why you should never ever call any class methods without making sure you have an object of that class.

NO :scream::

echo $page->file()->url()

YES :grinning::

if($file = $page->file()) {
  echo $file->url();
}

And so on…

0 Likes

#7

Ah now I understand why to check before use.

Thank you @texnixe.

0 Likes