0

I have translation file named as messages.en.yml file on the location <My-Bundle>/Resources/translations as follow:

company:
    messages:
        schedule:
            success:  Schedule saved successfully
            failed:   Something went wrong on saving schedule

Now I need to call this message by key on here:

$this->get('session')->getFlashBag()->add(
    'success',
    '%company.messages.schedule.success%'
);

I try many ways but not able to fix this.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
nifCody
  • 2,394
  • 3
  • 34
  • 54
  • 1
    Possible duplicate of [Translate the Flash Message](https://stackoverflow.com/questions/28588839/translate-the-flash-message) – gp_sflover Jan 25 '18 at 11:22

2 Answers2

3

try this

$this->get('session')->getFlashBag()->add(
'success',
$this->get('translator')->trans('company.messages.schedule.success')
);

also, need to enable in configuration:

framework:
    default_locale: 'en'
    translator:
        fallbacks: ['en']

Check official documentation: Symfony Basic Translation

habibun
  • 1,552
  • 2
  • 14
  • 29
1

Unfortunately it is impossible to translate a key translation in the flash bag ...

You could create a custom service with as dependencies

  • Translator
  • The session

And then perform the translation yourself before adding the message to the flashBag

use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Translation\Translator;

class FlashBagTranslator
{
    /** @var Translator $translator */
    private $translator;

    /** @var FlashBag $flashBag */
    private $flashBag;

    public function __construct(Translator $translator, Session $session)
    {
        $this->translator = $translator;
        $this->flashBag = $session->getFlashBag();
    }

    public function addMessage($type, $translationKey, array $parameters = [], $domain = null, $locale = null)
    {
        $message = $this->translator->trans($translationKey, $parameters, $domain, $locale);
        if ($message === $translationKey) {
            // Your translation isn't findable, do something :)
            return false;
        }

        $this->flashBag->add($type, $message);
        return true;
    }
}

A little disappointing, isn't it ?

Mcsky
  • 1,426
  • 1
  • 10
  • 20