如何检测Image Filename是否已更改?

时间:2017-11-09 21:32:11

标签: silverstripe

我需要检查我的图像的文件名是否已更改,如果是,那么我需要更新Slug数据库字段。我在onBeforeWrite()内尝试了以下内容,但它似乎没有检测到这种变化。

<?php
class TourPhoto extends DataObject {

    private static $db = array(
        'Slug' => 'Varchar(255)'
    );

    private static $has_one = array(
        'Image' => 'Image',
    );


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

        if ($this->Image()->isChanged('Name')) {
            // Update slug in here...
            $this->Slug = $this->Image()->Name;
        }
    }

}

enter image description here

1 个答案:

答案 0 :(得分:2)

这不起作用的原因是,只要保存onBeforeWrite,就会调用TourPhoto,而不是在保存Image时。保存Name时会更改Image

你可以尝试两件事。添加一个Image扩展程序,其中包含onBeforeWrite,其中您将获取链接到您的图片的TourPhotos并更新其slug。

这样的事情:

class ImageExtension extends DataExtension
{
    private static $has_many = array(
        'TourPhotos' => 'TourPhoto'
    );

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

        if ($this->owner->isChanged('Name')) {
            foreach ($this->owner->TourPhotos() as $tourPhoto) {
                $tourPhoto->Slug = $this->owner->Name;
                $tourPhoto->write();
            }
        }
    }
}

然后在mysite/config.yml

Image:
  extensions:
    - ImageExtension

或者您可以让TourPhoto onBeforeWrite检查slug是否与文件名不同,然后更新它。

class TourPhoto extends DataObject
{
    private static $db = array(
        'Slug' => 'Varchar(255)'
    );

    private static $has_one = array(
        'Image' => 'Image'
    );

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

        if ($this->Image()->exists() && $this->Slug != $this->Image()->Name) {
            $this->Slug = $this->Image()->Name;
        }
    }
}