Symfony: Adding to the translator dynamically

UPDATE: Symfony: Adding messages to the translator dynamically (updated) contains an update to the post below

To add to the translator (eg. from the DB / by user / etc), you need to first create your own translator class or force Symfony to use the base one (otherwise it’ll compile things together and use a read-only one when it comes to accessing your site).

First, in your services.yml file;

    public: true
    alias: 'Symfony\Bundle\FrameworkBundle\Translation\Translator'

  class: Symfony\Bundle\FrameworkBundle\Translation\Translator
      - '@service_container'
      - '@translator.selector'
      - '%kernel.default_locale%'

This just tells Symfony to use the base translator, or alternatively you can use your own as follows;


  public: true
  alias: 'YourNamespace\YourTranslatorClassName'

From there you can add a listener or just need to obtain an instance of the Translator on-load, and add in any resources as required – eg;

your-listener / controller / etc;

use Symfony\Component\Translation\Loader\ArrayLoader


$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', ["my.word" => "Hello"], $translator->getLocale());

$translator is an instance of “Symfony\Component\Translation\Translator”.

More info;

Leave a Reply