Structure field with default url

Hello together,

I don’t know if the title of my post is as clear as I mentioned. I hope so.

I have a structure field to create a table of content. It contains:

  • Select field with the selection of the page
  • A number field to give it a number for the chapter
  • url field to link the pages on the website

My problem is. I want to fetch the url of each page automatically in this url field.

But I don’t really know how I can make it. hope you can help me.

Greetz
Markus

You don‘t need to store the page url at all, get it from the page id stored in your select field in your template by calling toPage(’,’) on the field.

Ok. But I don’t create the pages in this structure field.

The file looks like this:

    label: Inhaltsverzeichnis
    type: structure
    icon: list-numbers
    fields:
      inhaltsseite:
        label: Inhaltsseite
        type: select
        options: query
        query: site.children.published
      kapitel: fields/kapitel
      url: fields/urlverzeichnis
``
So, is your way then also possible?

But you select the pages here, don’t you? And from this information you can create the URL.

Yes I select the pages from this.

Could I use something like the solution you have posted here:

It works like this:

<?php
// replace structurefieldname with name of your field, it's missing from your blueprint definition above
$items = $page->structurefieldname()->toStructure();
foreach ( $items as $item ) :
  if ( $p = $item->inhaltsseite()->toPage() ):
    // from here on, you have a page object and can get all its props
    echo $page->title();
    echo $page->url();
  endif;
endforeach;
?>

Thanks for your answer.

I have replace the structurefieldname with the field name which I need.
But now the browser shows me:

ParseError
syntax error, unexpected 'endforeach' (T_ENDFOREACH)

It’s not important anymore. This idea is actually something to high for my knowledge of PHP.
So, I will look after an easier solution.

Thanks for your time.

I corrected my code above, I used a curly brace instead of a colon.

1 Like

Thx a lot. Now it works.

I have tested an alternative way.

   <?php foreach ($page->inhaltsverzeichnis()->toStructure() as $toc): ?>

  <li>
    <?= $toc->kapitel() ?> <a href="<?= $toc->url() ?>"><?= $toc->inhaltsseite() ?></a>
    <div>
      <?= $toc->kurzText() ?>
    </div>
  </li>

<?php endforeach ?>

Now it shows also the url of each link.