Template syntax for a SiteConfig with a has_many DataObject

Silverstripe Version:



Hi all. Following the CMS Docs I’ve created an extension to SiteConfig with a has_many relationship to a DataObject. I am able to add records/data within the Settings just fine. What I’m having trouble with is the correct syntax to pull data from the has_many DataObject from within my template. I’m fairly new to this version of SS and would appreciate a nudge in the right direction, or an example if possible.

Thank you.

// Include any relevant code. If you have a lot of code, link to a gist instead.

The has_many relation will return a data list to the template, so you should be able to just loop over it:

<% loop $SiteConfig.SomeRelationOfStuff %>
 $Title <!-- Whatever the field on the related dataobject is called -->
<% end_loop %>

You should be able to get all the usual controls, data, etc. from inside the loop: https://docs.silverstripe.org/en/4/developer_guides/templates/syntax/#looping-over-lists

Thanks for your reply. That’s what I thought too and was the way I coded it first, but it’s still not working. here’s the important bits of my code, in case I’m doing something wrong. I’ve left out the rest.:

DataObject: Building.php

    private static $db = [
        'Name' => 'Varchar',

    private static $has_one = [
        'SiteConfig' => SiteConfig::class,

Data Extension: CustomSiteConfig.php

private static $has_many = [
    'Buildings' => Building::class,


    - CustomSiteConfig


<% loop $SiteConfig.Buildings %>
<% end_loop %>

When you say it’s not working… is there an error, no output at all, something else?

If you add some other content in the loop, does that get added to the page?
eg. change it to <p class="buildingname">Building: $Name</p>

Having some extra markup in there might help you to see if the loop is actually iterating (and hence the issue is with the $Name variable), or nothing is happening (and hence the issue is with the loop not working)

No errors & no output. I have tried adding the paragraph tags as you suggested, and there is no output at all, not even the para tags. When I loop on $SiteConfig alone, it prints that data just fine. It seems like $SiteConfig.Buildings isn’t return a DataList to loop on.

I think I’m on to something. I looked at the contents of the Building and SiteConfig db tables and while the Building records have a SiteConfigID field with a value of 0, the SiteConfig table record has an ID field of 2. I change the Building fields to 2 and the template loop now iterates through all entries properly. Down side is that when I enter a new Building the SiteConfigID field defaults to 0. I’ll try changing SiteConfig ID to 0 and see what happens, but I might just rebuild the the tables from scratch. At least I’m moving forward. I thank you for your help and suggestions!

Hi vancek,

Please try:

<% with $SiteConfig.Buildings %>

instead of loop