0

I'm implementing Cakephp 3 Translate behavior in my website but when I'm creating when the current language is not the default language all the other languages including the original entity are empty.

For example the available languages are: English (Default language), Dutch, French and Polish. When my website is switched to French and I create a entity the entity is empty when I switch to my default language. This is very confusing because my CMS now contains several empty entities

Does anyone have a solution for this?

Maat
  • 21
  • 5

1 Answers1

0

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);
    }
}
Maat
  • 21
  • 5