Automatically Publish Files

silverstripe-4
module
Tags: #<Tag:0x00007f10ca5813d0> #<Tag:0x00007f10ca581268>

#1

I am using SilverStripe 4 and the client doesn’t want to use draft files, basically whenever a file is uploaded or edited, I want to automatically publish any changes.

I have tried adding the following:

namespace App\Extensions;

use SilverStripe\ORM\DataExtension;

class FileExtension extends DataExtension
{
    /**
     * Automatically publish all files when written
     * 
     * @return null
     */
    public function onAfterWrite()
    {
        if (!$this->getOwner()->isPublished()) {
            $this->getOwner()->copyVersionToStage("Stage", "Live");
        }
    }
}

But this causes a nested error (some form of infinite loop). It appears that isPublished is always returning false.

I have also tried checking File::isChanged() and File::getChangedFields() and seems to fix the issue correctly.

Has anyone done anyone something similar? Any ideas on how to get this working would be greatly appreciated…


#2

For the most part, this is fixed with the below.

I am a little uncomfortable just automatically calling a ‘publishRecursive’ without any form of checks though, I guess I will have to do a bit more digging…

namespace App\Extensions;

use SilverStripe\ORM\DataExtension;

class FileExtension extends DataExtension
{
    /**
     * Automatically publish all files when written
     * 
     * @return null
     */
    public function onAfterWrite()
    {
            $this->getOwner()->publishRecursive();
    }
}