Skip to content

Commit aecd17c

Browse files
authored
Add validation for translated strings
1 parent 78710da commit aecd17c

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

classes/TranslatableBehavior.php

+29-12
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,26 @@ public function __construct($model)
8383
}
8484
});
8585

86-
$this->model->bindEvent('model.saveInternal', function() {
86+
$this->model->bindEvent('model.getValidationAttributes', function ($attributes) {
87+
if (($locale = $this->translateContext()) !== $this->translatableDefault) {
88+
foreach ($this->getTranslateDirty($locale) as $key => $value) {
89+
if (!empty($value)) {
90+
$attributes[$key] = $value;
91+
}
92+
}
93+
return $attributes;
94+
}
95+
}, 1000);
96+
97+
$this->model->bindEvent('model.saveInternal', function () {
8798
$this->syncTranslatableAttributes();
99+
100+
if (method_exists($this->model, 'validate')) {
101+
foreach ($this->getDirtyLocales() as $locale) {
102+
$this->translateContext($locale);
103+
$this->model->validate();
104+
}
105+
}
88106
});
89107
}
90108

@@ -316,25 +334,24 @@ public function syncTranslatableAttributes()
316334
}
317335

318336
/**
319-
* Changes the active language for this model
320-
* @param string $context
321-
* @return void
337+
* Change the active language for this model
338+
* @param string|null $context
339+
* @return string
322340
*/
323-
public function translateContext($context = null)
341+
public function translateContext($context = null): string
324342
{
325-
if ($context === null) {
326-
return $this->translatableContext;
343+
if ($context) {
344+
$this->translatableContext = $context;
327345
}
328-
329-
$this->translatableContext = $context;
346+
return $this->translatableContext;
330347
}
331348

332349
/**
333-
* Shorthand for translateContext method, and chainable.
334-
* @param string $context
350+
* Chainable shorthand for translateContext method
351+
* @param string|null $context
335352
* @return self
336353
*/
337-
public function lang($context = null)
354+
public function lang($context = null): self
338355
{
339356
$this->translateContext($context);
340357

0 commit comments

Comments
 (0)