php - Cakephp 3 Save translation first. Original entity later
one text
Solution:
I found a solution. I've created a custom TranslateBehavior which extends the default TranslateBehavior.
In my custom TranslateBehavior i've overwritten the afterSave event and filled the original entity with my translation data if the original entity was empty:
<?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);
}
}
Source