Skip to content

Commit 12dcff6

Browse files
zarubajdg
authored andcommitted
Validator::formatMessage() label is translated using form translator (#237)
1 parent f03a237 commit 12dcff6

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/Forms/Validator.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,17 @@ public static function formatMessage(Rule $rule, bool $withValue = true)
6565
$message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : null);
6666
}
6767

68-
$message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function (array $m) use ($rule, $withValue) {
68+
$message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function (array $m) use ($rule, $withValue, $translator) {
6969
static $i = -1;
7070
switch ($m[1]) {
7171
case 'name': return $rule->control->getName();
7272
case 'label':
7373
if ($rule->control instanceof Controls\BaseControl) {
74-
$caption = $rule->control->translate($rule->control->getCaption());
75-
return rtrim($caption instanceof Nette\Utils\Html ? $caption->getText() : $caption, ':');
74+
$caption = $rule->control->getCaption();
75+
$caption = $caption instanceof Nette\Utils\IHtmlString
76+
? $caption->getText()
77+
: ($translator ? $translator->translate($caption) : $caption);
78+
return rtrim($caption, ':');
7679
}
7780
return '';
7881
case 'value': return $withValue ? $rule->control->getValue() : $m[0];

tests/Forms/Controls.BaseControl.phpt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,37 @@ test(function () { // disabled & submitted
145145

146146
Assert::same('default', $input->getValue());
147147
});
148+
149+
150+
test(function () {
151+
$form = new Form;
152+
$form->setTranslator(new class implements Nette\Localization\ITranslator {
153+
public function translate($s, ...$parameters): string
154+
{
155+
return strtolower($s);
156+
}
157+
});
158+
159+
Validator::$messages[Form::FILLED] = '"%label" field is required.';
160+
161+
$input = $form->addSelect('list1', 'LIST', [
162+
'a' => 'First',
163+
0 => 'Second',
164+
])->setRequired();
165+
166+
$input->validate();
167+
168+
Assert::match('<label for="frm-list1">list</label>', (string) $input->getLabel());
169+
Assert::same(['"list" field is required.'], $input->getErrors());
170+
171+
$input = $form->addSelect('list2', 'LIST', [
172+
'a' => 'First',
173+
0 => 'Second',
174+
])->setTranslator(null)
175+
->setRequired();
176+
177+
$input->validate();
178+
179+
Assert::match('<label for="frm-list2">list</label>', (string) $input->getLabel());
180+
Assert::same(['"list" field is required.'], $input->getErrors());
181+
});

0 commit comments

Comments
 (0)