Search code examples
phpsilverstripesilverstripe-4

How to automaticly publish images in silverstripe dataextension


I was trying to add an uploadfield to a Custom DataExtension and got the Image field working. However the image i uploaded stays in concept mode, and i have to go to the File tab to publish it. I tried to use the code provided in the Silverstripe documentation but this only seems to work on regular pages. I found a question similar to mine:How to automaticaly publish files uploaded to a dataobject in Silverstripe model admin however this only seems to work on DataObjects.

This is my current code:

<?php
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\AssetAdmin\Forms\UploadField;
use SilverStripe\Assets\Image;
use SilverStripe\Assets\Storage\AssetStore;
use SilverStripe\Versioned\Versioned;
use SilverStripe\ORM\DataExtension;

class CustomSiteConfig extends DataExtension 
{   
    private static $db = [          
    ];      

    private static $has_one = [
        'Logo' => Image::class
    ];  

    private static $owns = [
        'Logo'
    ];  

    private static $extensions = [
        Versioned::class,
    ];  

    private static $versioned_gridfield_extensions = true;  

    public function updateCMSFields(FieldList $fields) 
    {
        $fields->addFieldToTab("Root.Header", LiteralField::create("","<h1>Header</h1>"));                  
        $fields->addFieldToTab("Root.Header", UploadField::create('Logo', 'Logo'));                     
    }       
}

Does anyone know a solution?


Solution

  • There's currently a bug that prevents "owned" records to be published if the owning dataobject is not versioned.

    I think you're experience this bug, since SiteConfig is not versioned and thus won't publish owned files/images when it's being saved.

    Until this bug has been resolved, you could use an onAfterWrite hook in your extension to publish the file:

    public function onAfterWrite()
    {
        if ($this->owner->LogoID) {
            $this->owner->Logo()->publishSingle();
        }
    }