假设我有此表单:
//...
class BananaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('flavor');
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
if ($form->get('flavor')->getData() === null) {
$form->addError(new FormError('form.error.flavor_missing'));
}
}
}
}
即使在messages.yml和validators.yml中都定义了消息 form.error.flavor_missing ,它也不会显示。
任何想法如何翻译?我希望我不必为了解决这个问题而以每种形式注入translator
服务。
答案 0 :(得分:0)
为什么不使用Validation Constraints
use Symfony\Component\Validator\Constraints as Assert;
// ...
class BananaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('flavor', YourType::class, array(
'constraints' => array(
new Assert\NotNull(), // or any other
),
));
}
}
您可以使用自定义消息
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('flavor', YourType::class, array(
'constraints' => array(
new Assert\NotNull(array(
'message' => 'form.error.flavor_missing'
)),
),
));
}
答案 1 :(得分:0)
如果打开开发环境,则应该看到缺少的字符串。看看它们,您应该会看到域和预期的消息文件。