From aecd17c42007c7f3d28e0dad0941c1a36a7c74d0 Mon Sep 17 00:00:00 2001 From: Marc Jauvin Date: Mon, 18 Mar 2024 14:22:58 -0400 Subject: [PATCH] Add validation for translated strings --- classes/TranslatableBehavior.php | 41 ++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/classes/TranslatableBehavior.php b/classes/TranslatableBehavior.php index 1a124d8..b313489 100644 --- a/classes/TranslatableBehavior.php +++ b/classes/TranslatableBehavior.php @@ -83,8 +83,26 @@ public function __construct($model) } }); - $this->model->bindEvent('model.saveInternal', function() { + $this->model->bindEvent('model.getValidationAttributes', function ($attributes) { + if (($locale = $this->translateContext()) !== $this->translatableDefault) { + foreach ($this->getTranslateDirty($locale) as $key => $value) { + if (!empty($value)) { + $attributes[$key] = $value; + } + } + return $attributes; + } + }, 1000); + + $this->model->bindEvent('model.saveInternal', function () { $this->syncTranslatableAttributes(); + + if (method_exists($this->model, 'validate')) { + foreach ($this->getDirtyLocales() as $locale) { + $this->translateContext($locale); + $this->model->validate(); + } + } }); } @@ -316,25 +334,24 @@ public function syncTranslatableAttributes() } /** - * Changes the active language for this model - * @param string $context - * @return void + * Change the active language for this model + * @param string|null $context + * @return string */ - public function translateContext($context = null) + public function translateContext($context = null): string { - if ($context === null) { - return $this->translatableContext; + if ($context) { + $this->translatableContext = $context; } - - $this->translatableContext = $context; + return $this->translatableContext; } /** - * Shorthand for translateContext method, and chainable. - * @param string $context + * Chainable shorthand for translateContext method + * @param string|null $context * @return self */ - public function lang($context = null) + public function lang($context = null): self { $this->translateContext($context);