Search code examples
phpsilverstripesilverstripe-4

How to set & lock SiteTree in Silverstripe 4?


We're working on a project where Silverstripe acts as headless CMS with a single API data point.

The content is all from non-SiteTree dataobjects & the API data point is the only SiteTree record we need.

What is the best way of making sure the API data point exists & it is the only SiteTree record on each /dev/build. We could then disable PagesAdmin in LeftAndMain so users couldn't edit/ break it.

I've found code here which would look a bit like this for our case:

$api = new API/AccessPoint();
$api->Title = 'API';
$api->URLSegment = 'home';
$api->ShowInMenus = '1';
$api->Version = '1';
$api->ParentID = '0';
$api->write();
$api->doRestoreToStage();

But I'm not sure of the correct approach for making sure that a dev\build removes all the other pages & creates 1 record of this page.

Any help would be appreciated.


Solution

  • You can use requireDefaultRecords() in your DataObject to create records on a dev/build. You'll need to do some kind of check before creating a new one though, e.g.

    public function requireDefaultRecords()
    {
        parent::requireDefaultRecords();
    
        if (AccessPoint::get()->filter('URLSegment', 'home')->exists()) {
            return;
        }
    
        // create your new object here
    }