Cant display video - "call to a member function url() on null"

Hi - I have a file field inside the event yml. all the events must have a file.
The file can be either an image or a video.
I tried to create an if statement that says: if the file is image show image and if the file is video show a video.
I wrote this bit of code inside the event.php:

<?php if ($tmuna->file()->type()== 'image'):?>
    <div class='big-img-wrap'><img class='feature-image' src='<?=$tmuna->image()->url() ?>'></div>
<?php endif ?>
<?php if ($tmuna->file()->type()== 'video'):?>
    <video width="300" height="200"  >
        <source src="<?= $tmuna->image()->url() ?>" type="video/mp4">
<?php endif ?>

The result of this code is “call to a member function url() on null”
Any idea why?

Thanks in advance!

When you get this error message, it means that the object ($tmuna->image() in this case) does not exist.

Never use any dynamic class methods without checking if you have an object of this class.

Don’t quite understand why you have two calls to $tmuna->image() although you are checking for the type of the first file in the page. So what are you actually trying to do here? Are you inside a loop?

Hi - thanks for the reply.
I am inside a foreach loop - yes.
I want to detect if the type of the file is a video or an image and according to the result showing either a video tag or an image tag. does it make sense?

I’ve added an if statement before to check if the file exist and inside of it inserted the ‘if video or image statement’. now I managed to remove the error - but the video doesn’t exist. it shows the events with the images but not the video ones (and I have a video file in the content of some events)

Any idea if my code that tries to detect if the file is a video or an image is correct?
This is my new code:

$tmunot = page()->children()->template('tmuna');
foreach ($tmunot as $tmuna) : ?>
    <div class='tmuna switch'>
    <div class='today-events'>
        <?php if($file = $tmuna->file()): ?>
            <?php if($file->type() == 'image'):?>
                <div class='big-img-wrap'><img class='feature-image' src='<?=$file->url() ?>'></div>
            <?php elseif ($file->type() == 'video'): ?>
                <video width="300" height="200"  >
                     <source src="<?= $file->url() ?>" type="video/mp4">
            <?php endif; ?>
        <?php endif; ?> 
<?php endforeach ?>


Yes, the code is ok like that.

What do you get for the events with videos? Nothing at all?

1 Like