kdyby/Translation to be used in formFactory

Notice: This thread is very old.
pedro
Member | 1
+
0
-

Hello,
I did this:

composer create-project nette/sandbox testTranslation
cd testTranslation
composer require kdyby/translation

I created the folder testTranslation/app/lang with 2 text files:
lang.es_ES.neon and lang.en_US.neon

Inside each of them I put some translation of hello world:

main:
	hello: "Hello world"

next I did setup as described in github kdyby/translation/quickstart.

abstract class BasePresenter extends Nette\Application\UI\Presenter
{
    /** @persistent */
    public $locale;

    /** @var \Kdyby\Translation\Translator @inject */
    public $translator;

    // rest of your BasePresenter
}
  • in line 23 in routerFactory.php changed this line to this:
$router[] = new Route('[<locale=cs cs|en>/]<presenter>/<action>[/<id>]', 'Homepage:default'); ?>
  • modified the app/config/config.neon to set default language and register the extention Translation

… and so on.

Finally it works as expected in homepage/default.latte. In the presenters the method $this->translator->translate(); also works great.

The question I have is How to use the translation in the class app/forms/SignFactory? I do not know how to get there the object $this->translator to use the method translate() for example. Or other suggested method how to use kdyby/translation in formFactory?

David Matějka
Moderator | 6445
+
+1
-

You can inject Nette\Localization\ITranslator using constructor (or directly Kdyby\Translation\Translator – it doesn't matter, it implements that interface):

class SignFormFactory extends Nette\Object
{

	private $translator;

	public function __construct(\Nette\Localization\ITranslator $translator)
	{
		$this->translator = $translator;
	}

	/**
	 * @return Form
	 */
	public function create()
	{
		$form = new Form;
		$form->setTranslator($this->translator);

		....
	}
}

Nette will translate labels, error messages etc. using that translator.

There is a great article describing usage of DI ;)