Output page url in structure?

Have the following structure field:

homepagelinks:
    type: structure
    columns:
      text:
        width: 1/2
      link:
        width: 1/2
    fields:
      text:
        type: text
      link:
        type: pages
        multiple: false

For markup reasons I can’t loop trough the structure but need to access them directly.
I’m using this to get the array:

$links = $page->homepagelinks()->yaml();

and I can access the text fine like this:

<?= $links[0]['text'] ?>

but I’m unable to output the page url, always get “Call to a member function toPage() on array” or “array to string conversion” errors…
So how do I output the page url?
This:

<?= $links[0]['link'] ?>

gives an error.
This:

<?= $links[0]['link']->toPage()->url() ?>

also.

toPage() is a field method, but you are working with an array, so this doesn’t work and you would have to use the page() helper and have to pass your page id/uuid to the helper. But there is one caveat: The value is stored as yaml array, so a single page with a preceding dash.

If I were you, I’d still work with the StructureObject, you don’t have to loop through the Structure but can access individual items just the same as you do with your array, only more comfortable:

<?php
$links         = $page->homepagelinks()->toStructure();
$firstItem     = $links->first();
$firstItemPage = $firstItem?->link()?->toPage();

// or all in one
$url1 = $firstItem?->link()?->toPage()?->url(); // using the null-safe operator!

Instead of first, you can use nth() to get individual items.

1 Like

Awesome, many thanks for the speedy reply, have to use this several times in this project. Cheers!