<?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);
}
}
1条答案
按热度按时间5f0d552i1#
我找到了一个解决方案。我创建了一个自定义的TranslateBehavior,它扩展了默认的TranslateBehavior。
在我的自定义TranslateBehavior中,我已经覆盖了afterSave事件,并且如果原始实体为空,则用我的翻译数据填充原始实体: