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.

Data Model Questions /

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

[Solved] Trouble updating Page data and writing to database.


Go to End


2 Posts   1346 Views

Avatar
Sticks

Community Member, 31 Posts

25 September 2014 at 1:05pm

Hi guys,

I'm trying to update a field in a bunch of pages and write the change from a custom SiteConfig extension. The problem is the page isn't writing or publishing to the database.

I have a field on the SiteConfig for example called "LockAllPages". When this field is ticked in the site settings and saved I then want to change a field on each page called "LockedPage" to be 'true' (or false, depending on the change).

I'm using the Subsites module. The code I'm using to try to update the Pages of a website is below.

<?php
    class CustomSiteConfig extends DataExtension {

        // Goes through each page and updates their security
        // based on LockAllPages value in SiteConfig
        public function updateLockedPages() {

            // Get all Pages on this Subsite
            $SubsiteID = Subsite::currentSubsite()->ID;
            $Pages = Page::get()->filter(array(
                'ID' => $SubsiteID
            ));

            // Go Through each page and update LockedPage value
            foreach($Pages as $Page) {
                $Page->LockedPage = (string)$this->owner->LockAllPages;
                $Page->write(); 
                $Page->publish('Stage', 'Live');
            }
        }

        public function onBeforeWrite() {
            parent::onBeforeWrite();
            $this->updateLockAllPages();
        }

    }

I've tried a tonne of combinations of $Page->write(), $Page->doPublish(), $Page->writeToStage('Stage'), and so far none seem to affect the database.

I'm thinking the problem might be in how I'm getting the pages with the Page::get() function. I'm looking in the page and page_live tables for the updates.

Thanks in advance for your help!

Avatar
Sticks

Community Member, 31 Posts

25 September 2014 at 3:12pm

OK, all fixed. Simple error was to blame here. The filter on the Page::get() should've been on 'SubsiteID' instead of 'ID' as below.

// Get all Pages on this Subsite 
$SubsiteID = Subsite::currentSubsite()->ID; 
$Pages = Page::get()->filter(array( 
    'SubsiteID' => $SubsiteID 
));

For the record, the lines to write to the database (and publish) that work for me are these two:

$Page->writeToStage('Stage');
$Page->publish('Stage', 'Live');

And I forgot to mention this is on SS 3.1