Perry
April 12, 2019, 11:46am
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
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.
Perry
April 12, 2019, 12:13pm
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 ?
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 )
Perry
April 12, 2019, 12:30pm
5
texnixe:
<?php if($image2 = $single_image->gallery_img()->toFile()): ?> <?php $thumb = $image2? $image2->resize(2000)->url(): ''; ?> <?php endif ?>
Okay thank you, now it works.
Call to a member function srcset() on null
Does that mean a image field gallery_img() in the structure field is empty ?
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 :
echo $page->file()->url()
YES :
if($file = $page->file()) {
echo $file->url();
}
And so on…
Perry
April 12, 2019, 12:36pm
7
Ah now I understand why to check before use.
Thank you @texnixe .