How can I write php code if I have a relational article in the structure?
If I write both codes at the same time, it gives me an error.
Blueprint (Blueprints work fine.)
project:
label: list
type: structure
fields:
related:
label: link page
type: pages
query: site.find('cyborgthinks').children.listed
php templete
<?php foreach ($page->project()->toStructure() as $project):
$p= $page->related()->toPages();
if($p):
?>
<li>
...
<a href="<?php echo $p->url() ?>">read more</a>
...
</li>
<?php endif ?>
<?php endforeach ?>
- Why do you use a structure field? The pages field lets you select multiple pages, so no need for the structure field.
- If you want to stick with the structure field for some reason, it might make sense to limit the pages field to
max: 1
, so that only a single page can be selected per structure field item.
In case of No. 2 and 1 page per field, you code would have to look like this:
<?php foreach ($page->project()->toStructure() as $project):
if ($p = $page->related()->toPage()): ?>
<li>
...
<a href="<?php echo $p->url() ?>">read more</a>
...
</li>
<?php endif ?>
<?php endforeach ?>
In case you decide to go with just the pages field:
Blueprint:
related:
label: link page
type: pages
query: site.find('cyborgthinks').children.listed
Template:
<?php foreach ($page->related()->toPages() as $p): ?>
<li>
<a href="<?php echo $p->url() ?>">read more</a>
</li>
<?php endforeach ?>