Search code examples
phpsilverstripesilverstripe-4

How to show manually published owned objects updated non-draft status on save?


this question explains how to add code to publish owned objects from objects which are not Versioned.

Using basically the same code without the owner part (because we are using extended DataObjects not Extensions), the owned objects are published when the objects are saved, but the owned objects UI interface is not updated so the untrained or forgetful user doesn't know that their owned object is actually published.

Here is the source code that publishes owned objects on an object that is not versioned:

class SomeDataObject extends DataObject
{
    private static $has_one = [
        'SomeFileThatIsVersioned'  => File::class,
    ]

    // somewhat pointless owns declaration
    private static $owns = [
        'SomeFileThatIsVersioned',
    ];

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

        // Manually force publish since owns doesn't work when object is not Versioned
        $ownsKeys = array_keys(self::$owns);
        foreach ($ownsKeys as $key) {
            $keyID = $key . "ID";
            if ($this->$keyID) {
                $this->$key()->publishSingle();
            }
        }
    }

Appearance after save

Notice that the pseudo-"owned" object still shows as Draft enter image description here


Appearance after save and page refresh

Notice how pseudo-"owned" object no longer shows Draft status. enter image description here


Solution

  • I'm afraid that's a bug in SilverStripe and I am not aware of an easy fix. There is an open issue already for it: https://github.com/silverstripe/silverstripe-asset-admin/issues/960


    Sidenote: don't use self::$owns, SilverStripe does some magic shenanigans with private statics (merges them into the config), so your use here breaks with the admittedly odd convention in SilverStripe.

    It might be better to use self::config()->get('owns') or self::config()->uninherited('owns').
    This would stay in line with SilverStripe conventions where you can add extra items via the config system (Config::inst()->.... or a yml file), aswell as supprting mergin inherited values if you use self::config()->get('owns').