Howto: Translation in Symfony Forms

It comes up on the symfony Mailinglist all the time: How do I use the translation helpers in symfony Form classes. Here it is...

The key to using tranlations in symfony form classes is to somehow access the i18n Object. This can be done in two ways:

First way: use the sfContext Object like:

sfContext::getInstance()->getI18n()->__('text);

This is BAD and you should NEVER EVER do this. Please refer to the excellent article of Berhard Schussek "Why sfContext::getInstance() Is Bad"

Second way (the only real way): Pass the i18n object to the form. you can do it in your action with something like

$form = new myForm(array(), array("i18n" => $this -> getContext() -> getI18n()));

And in the form class get the option with

$i18n = $this -> getOption("i18n");
$i18n -> __('My Translated Text');

Please remember to never call sfContext::getInstance in your Model or Form classes, otherwise it will result in untestable code.