How to print field of page or parent page (if it's in parent page)?

I would like to show same image in the footer, as in header. I am using this solution:

id="footer"
class="footer" 
<?php if ($page->background()->isNotEmpty()): ?>
                    style="
                    background:url(<?= $page->background()->toFile()->url() ?>);
                    background-position: center center;
                    background-size: cover;
                    "
 <?php endif ?>

On this page http://metalista.lt.grikis.serveriai.lt/en/paslaugos/technologines-irangos-gamyba I am showing header image of parent page. So for example this child also has the same header of parent: http://metalista.lt.grikis.serveriai.lt/en/paslaugos/subranga

If I am trying to get background of parent:

id="footer"
class="footer" 
<?php if ($page->parent()->background()->isNotEmpty()): ?>
                    style="
                    background:url(<?= $page->parent()->background()->toFile()->url() ?>);
                    background-position: center center;
                    background-size: cover;
                    "
 <?php endif ?>

then I am getting error on pages, that don’t have parent page with this field.

So how could I check both page and parent page, if it has this field, and then print this field in footer?

<?php
$background = $page->background()->toFile() ?? $page->parent()->background()->toFile();

if ($background): ?>
                    style="
                    background:url(<?= $background->url() ?>);
                    background-position: center center;
                    background-size: cover;
                    "
 <?php endif ?>

Never call a method (in this case url()) without asserting the object exists.

1 Like

Ah, easy, thank you! Working perfect.

Sorry, was too fast to reply. On frontpage getting error: Call to a member function background() on null
Not all pages have this field.

The problem is not the missing field but the missing parent. This should fix it:

$background = $page->background()->toFile() ?? $page->parent() ? $page->parent()->background()->toFile() : null;

Frontpage is ok now, but error on pages, that probably don’t have children (frontpage has): Call to a member function background() on null
for example this http://metalista.lt.grikis.serveriai.lt/en/contact

Maybe we have to wrap the last part in brackets, try this:

$background = $page->background()->toFile() ?? ($page->parent() ? $page->parent()->background()->toFile() : null);
1 Like

Yes, now it’s working on all pages, thanks a lot!