Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

[Solved] has_one + has_many relationship not working


Go to End


2 Posts   743 Views

Avatar
Vlad Belfort

Community Member, 55 Posts

26 April 2016 at 4:04am

I have a dropdown field available on all page types throughout my site in Page.php which allows the user to specify which sites can see that content.

For some reason when a site is selected from the dropdown list; the ID is sent in the response but the value is not stored in the SiteID column for that article...

Page.php

class Page extends SiteTree {
# ...
    private static $has_one = array(
        'Site' => 'Site'
    );

    public function getSettingsFields(){

        $fields = parent::getSettingsFields();

        $sites = new DropdownField('Site', 'Select a site that will see this article', Site::getListOfSites());
        $sites->setEmptyString('All');
        $fields->addFieldToTab('Root.Settings', $sites);

        return $fields;

    }
# ...
}

Site.php

class Site extends DataObject {

    private static $db = array(
        'Title' => 'Varchar(255)',
        'Code' => 'Varchar(20)',
        'TimeZone' => 'Varchar(20)' // UTC+0:00,   UTC-7:00
    );

    private static $has_one = array(
    );

    private static $has_many = array(
        'Pages' => 'Page'
    );

    public function getListOfSites(){

        if($sites = DataObject::get('Site'))
            return $sites->map('ID', 'Title');
    }
# ...

What do I need in order for it to store the relevant ID to the pages SiteID column?..

Avatar
Vlad Belfort

Community Member, 55 Posts

26 April 2016 at 4:39am

Ah I just needed to put SiteID instead of Site when creating the dropdown...

$sites = new DropdownField('SiteID', 'Select a site that will see this article', Site::getListOfSites());