diff --git a/src/Model/Behavior/TranslateBehavior.php b/src/Model/Behavior/TranslateBehavior.php index d29549af39c..9714088bcea 100644 --- a/src/Model/Behavior/TranslateBehavior.php +++ b/src/Model/Behavior/TranslateBehavior.php @@ -149,7 +149,7 @@ public function beforeFind(Event $event, $query) { } public function beforeSave(Event $event, $entity) { - $locale = $this->locale(); + $locale = $entity->get('_locale') ?: $this->locale(); if (!$locale) { return; @@ -180,6 +180,8 @@ public function beforeSave(Event $event, $entity) { } $entity->set('_i18n', array_values($modified + $new)); + $entity->set('_locale', $locale, ['setter' => false]); + $entity->dirty('_locale', false); foreach ($fields as $field) { $entity->dirty($field, false); diff --git a/tests/TestCase/Model/Behavior/TranslateBehaviorTest.php b/tests/TestCase/Model/Behavior/TranslateBehaviorTest.php index 6943a87a26c..961a9fbefe4 100644 --- a/tests/TestCase/Model/Behavior/TranslateBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/TranslateBehaviorTest.php @@ -505,6 +505,7 @@ public function testInsertNewTranslations() { $this->assertEquals(1, $article->get('id')); $article->set('title', 'Le titre'); $table->save($article); + $this->assertEquals('fra', $article->get('_locale')); $article = $table->find()->first(); $this->assertEquals(1, $article->get('id')); @@ -520,4 +521,31 @@ public function testInsertNewTranslations() { $this->assertEquals('Le contenu', $article->get('body')); } +/** + * Tests that it is possible to use the _locale property to specify the language + * to use for saving an entity + * + * @return void + */ + public function testUpdateTranslationWithLocaleInEntity() { + $table = TableRegistry::get('Articles'); + $table->addBehavior('Translate', ['fields' => ['title', 'body']]); + $article = $table->find()->first(); + $this->assertEquals(1, $article->get('id')); + $article->set('_locale', 'fra'); + $article->set('title', 'Le titre'); + $table->save($article); + + $article = $table->find()->first(); + $this->assertEquals(1, $article->get('id')); + $this->assertEquals('First Article', $article->get('title')); + $this->assertEquals('First Article Body', $article->get('body')); + + $table->locale('fra'); + $article = $table->find()->first(); + $this->assertEquals(1, $article->get('id')); + $this->assertEquals('Le titre', $article->get('title')); + $this->assertEquals('First Article Body', $article->get('body')); + } + }