Cakephp 3首先保存翻译,然后保存原始实体

zu0ti5jz  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(166)

我在我的网站中实现Cakephp 3翻译行为,但当我创建时,当前语言不是默认语言,所有其他语言,包括原始实体都是空的。
例如,可用的语言有:英语(默认语言),荷兰语,法语和波兰语。当我的网站切换到法语,我创建了一个实体,当我切换到我的默认语言时,实体是空的。这是非常混乱的,因为我的CMS现在包含几个空实体
有人能解决这个问题吗?

5f0d552i

5f0d552i1#

我找到了一个解决方案。我创建了一个自定义的TranslateBehavior,它扩展了默认的TranslateBehavior。
在我的自定义TranslateBehavior中,我已经覆盖了afterSave事件,并且如果原始实体为空,则用我的翻译数据填充原始实体:

<?php
namespace App\Model\Behavior;

use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\I18n\I18n;
use Cake\ORM\Behavior\TranslateBehavior as BaseTranslateBehavior;
use Cake\ORM\TableRegistry;

/**
 * Translate behavior
 */
class TranslateBehavior extends BaseTranslateBehavior
{
    /**
     * Populate original untranslated entity with translated entity if original fields are strictly null
     *
     * @param Event $event            The beforeSave event that was fired
     * @param EntityInterface $entity Translated entity
     * @return void
     */
    public function afterSave(Event $event, EntityInterface $entity)
    {
        parent::afterSave($event, $entity);

        $defaultLocale = I18n::getDefaultLocale();
        $currentLocale = I18n::getLocale();

        // Skip if current locale is the default locale
        if ($currentLocale === $defaultLocale) {
            return;
        }

        // Get original entity
        $table = TableRegistry::getTableLocator()->get($entity->getSource());
        $table->setLocale($defaultLocale);

        $originalEntity = $table->get($entity->{$table->getPrimaryKey()});

        // Populate fields of original entity with translated entity if fields are strictly null
        $fields = $this->_config['fields'];
        foreach ($fields as $field) {
            if ($originalEntity->{$field} === null) {
                $originalEntity->{$field} = $entity->{$field};
            }
        }

        // Temp remove Translate behavior from table to prevent recursive
        $table->removeBehavior('Translate');

        // Save original entity
        $table->save($originalEntity);

        // Re-add Translate behavior
        $table->addBehavior('Translate', $this->_config);

        // Set locale back to current
        $table->setLocale($currentLocale);
    }
}

相关问题