5

I'm currently integrating the Symfony Validator Component into a custom PHP Application. So far, everything has been working pretty nice and I can validate my User input.

Now I want to translate the validation messages to another locale and have integrated the Translation Component (it's required anyway due to a depnedency with TranslatorInterface in the DefaultTranslator).

The default Translator only supports the locale that is hard coded into the ValidationConstraints. As far as I've figured it out, I need to specify a custom Translator instance that loads the strings from the xliff files in the Validator component.

This is how far I got but the german translation would sadly not load:

    $translator = new Translator('de_DE');
    $translator->setFallbackLocale('en_GB');
    $translator->addLoader('xliff', new XliffFileLoader());

    $builder = new ValidatorBuilder();
    $validator = $builder
            ->setTranslator($translator)
            ->getValidator();
    $violations = $validator->validateValue($input, self::getValidationConstraints());

Any suggestions what I might be missing out here?

room13
  • 1,922
  • 1
  • 15
  • 28

1 Answers1

5

Found out myself. Of course the translation files need to be loaded... Also the Symfony config component needs to be added due to a dependencie to the FileLoader class.

    $translator = new Translator('de');
    $translator->addLoader('xliff', new XliffFileLoader());
    $translator->addResource('xliff', '<path-to-compontnt>/Resources/translations/validators.de.xlf', 'de','validation');

    $builder = new ValidatorBuilder();
    $validator = $builder
            ->setTranslator($translator)
            ->setTranslationDomain('validation')
            ->getValidator();
room13
  • 1,922
  • 1
  • 15
  • 28
  • I was using the Symfony components outside of the Symfony2 framework, and also had problems getting translations to work. The official docs do not tell you to use the `ValidatorBuilder` class, so this answer is for those who have the same use case. Thanks! – KGC Oct 20 '16 at 11:52