Skip to content
Permalink
Browse files

Validator::formatMessage() label is translated using form translator (#…

  • Loading branch information
zarubaj authored and dg committed Nov 26, 2019
1 parent f03a237 commit 12dcff63bcb2e812699dfc0285c882ac8b88c4e4
Showing with 40 additions and 3 deletions.
  1. +6 −3 src/Forms/Validator.php
  2. +34 −0 tests/Forms/Controls.BaseControl.phpt
@@ -65,14 +65,17 @@ public static function formatMessage(Rule $rule, bool $withValue = true)
$message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : null);
}
$message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function (array $m) use ($rule, $withValue) {
$message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function (array $m) use ($rule, $withValue, $translator) {
static $i = -1;
switch ($m[1]) {
case 'name': return $rule->control->getName();
case 'label':
if ($rule->control instanceof Controls\BaseControl) {
$caption = $rule->control->translate($rule->control->getCaption());
return rtrim($caption instanceof Nette\Utils\Html ? $caption->getText() : $caption, ':');
$caption = $rule->control->getCaption();
$caption = $caption instanceof Nette\Utils\IHtmlString
? $caption->getText()
: ($translator ? $translator->translate($caption) : $caption);
return rtrim($caption, ':');
}
return '';
case 'value': return $withValue ? $rule->control->getValue() : $m[0];
@@ -145,3 +145,37 @@ test(function () { // disabled & submitted
Assert::same('default', $input->getValue());
});
test(function () {
$form = new Form;
$form->setTranslator(new class implements Nette\Localization\ITranslator {
public function translate($s, ...$parameters): string
{
return strtolower($s);
}
});
Validator::$messages[Form::FILLED] = '"%label" field is required.';
$input = $form->addSelect('list1', 'LIST', [
'a' => 'First',
0 => 'Second',
])->setRequired();
$input->validate();
Assert::match('<label for="frm-list1">list</label>', (string) $input->getLabel());
Assert::same(['"list" field is required.'], $input->getErrors());
$input = $form->addSelect('list2', 'LIST', [
'a' => 'First',
0 => 'Second',
])->setTranslator(null)
->setRequired();
$input->validate();
Assert::match('<label for="frm-list2">list</label>', (string) $input->getLabel());
Assert::same(['"list" field is required.'], $input->getErrors());
});

0 comments on commit 12dcff6

Please sign in to comment.
You can’t perform that action at this time.