BaronGrivet BaronGrivet - 1 month ago 7
PHP Question

How to set all possible relationships of has_many as default in SilverStripe

In our SilverStripe project

NavBlock
has_many
SiteModes
:

class NavBlock extends DataObject
{
private static $has_many = array(
'SiteModes' => 'SiteMode'
);
}


How do I set the default for
NavBlock
to have a
has_many
relationship with all available
SiteModes
?

I would like to have this relationship appear when a new
NavBlock
is created and applied to all existing
NavBlocks
.

What is the best way to achieve this?

Answer

One way to do this is to add each SiteMode in the class onAfterWrite function:

class NavBlock extends DataObject {

    private static $has_many = array(
        'SiteModes' => 'SiteMode'
    );

    protected function onAfterWrite() {
        parent::onAfterWrite();

        if ($this->SiteModes()->count() === 0) {
            $siteModes = SiteMode::get();

            foreach ($siteModes as $siteMode) {
                $this->SiteModes()->add($siteMode);
            }
        }
    }
}