我正在我的网站中实现 Cakephp 3 Translate 行为,但是当我创建当前语言不是默认语言时,包括原始实体在内的所有其他语言都是空的。
例如,可用的语言有:英语(默认语言)、荷兰语、法语和波兰语。当我的网站切换到法语并创建实体时,当我切换到默认语言时,该实体为空。这很令人困惑,因为我的 CMS 现在包含几个空实体
有人对此有解决方案吗?
我找到了解决方案。我创建了一个自定义的 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);
}
}