Strange error with link-field plugin

Hello,
here is a strange one for the weekend… I don’t know exactly if the problem is within the link field or if it’s a problem with the page()-Helper.

I have a snippet for the plugin and I’m want to set somekind of fallback linktext. So when the link is internal I thought, let’s just take the title of the page. And i have this code running:

$link = $linksrc->link()->yaml();
$linktarget = $link['link'];
if($linktype == 'page'){
  $targetpage =  page($linktarget);
  $linkalt = $target->title();
}

In may Case the $linksrc comes from a structured field. The $targetpage returns a complete pages-object as expected, but when when I try to call the title I just get a “Call to a member function title() on null” error.

Am I missing something? When I call the URI directly with the page()-Helper, everything works fine. Maybe @thguenther has clue how this could happen.

Otherwise the plugin works like a charm (it could be considered to implement a string encode for emails) and it’s not a dealbreaker here. I’m just very confused why this happens.

Cheers and have nice weekend
tom

The code is missing some context? Is that within a loop?

In any case, if $targetpage = page($linktarget); returns the page, why are you calling the title() method on $target()? Where is that variable defined?

And in any case, you should always check if you have an object before you call a method to avoid such errors:

if($linktype == 'page'){
  if($targetpage = page($linktarget)) {
    echo $targetpage->title();
  }
}

Incredible that you’re still answering at this time, thanks.
Yes it’s within a loop. And sorry it’was a typo in the post… $target is $targetpage. And I learned my lesson to check if the object exist. It’s not implemented yet, but it was the next thing to do before I run in to that error.

But as I said, the returned page-object looks just fine. Here is a screenshot of the dumped object with page($linktarget):

And the exact same page-object page(‘lage-umgebung’) - the example page:

The return objects are same, as far as I see. The only difference is, that the first one crashes when I try to call the content. The other works fine…

Yes, I’m crazy :crazy_face:.

Does it crash despite the if-statement I posted above?

Maybe you can post the stack trace as well… or the screenshot of the error page.

Heres the screenshot of the errorpage:

I go and try the if-statement, but could this really be the answer?

It usually is, because if one page works it doesn’t mean that the other pages work… Especially in loops, there is often one item that doesn’t return what is expected.

And once again you’re the hero. It works… I still don’t really get why though, but who needs to everything :sweat_smile:

Thanks again for responding and helping that quick. You do an awesome job here.

Have a really nice weekend

1 Like

Thanks, you too!