This is a really common one. It can be solved using the owns
api on versioned dataobjects, but we don’t yet have access to that for non-versioned objects (such as SiteConfig, for example). We’ll be able to use owns
on non-versioned dataobjects in 4.1 so that will help a lot, but until then the solution is to use publish single in onBeforeWrite (or onAfterWrite).
public function onBeforeWrite()
{
if($this->Image() && $this->Image()->exists()) {
$this->Image()->publishSingle();
}
parent::onBeforeWrite();
}
@zanderwar wrote some code that will do this generically by looping the has_one relations:
public function onBeforeWrite()
{
parent::onBeforeWrite();
/** @var Image $relation **/
foreach (static::$has_one as $key => $relation) {
if ($relation == Image::class && !$this->{$key}()->exists() && !$this->{$key}()->isPublished()) {
$this->{$key}()->publishSingle();
}
}
}