Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Slavenin
Last active May 26, 2017 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Slavenin/40ca0da8bfb5dbdc5d4da7ef38015887 to your computer and use it in GitHub Desktop.
Save Slavenin/40ca0da8bfb5dbdc5d4da7ef38015887 to your computer and use it in GitHub Desktop.
Symfony form extrension translator on createView
services:
app.translator_extension:
class: AppBundle\Form\Extension\TranslatorExtension
arguments: ['@translator']
tags:
- { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }
<?php
namespace KVZBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Translation\TranslatorInterface;
class TranslatorExtension extends AbstractTypeExtension
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* TranslatorExtension constructor.
* @param TranslatorInterface $translator
*/
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function finishView(FormView $view, FormInterface $form, array $options)
{
$domain = $form
->getConfig()
->getOption('translation_domain')
;
$this->translate($view->children, $domain);
}
private function translate(&$children, $domain, $locale = 'ru')
{
foreach ($children as $name => $child)
{
$children[$name]->vars['label'] = $this->translator->trans($child->vars['label'], [], $domain, $locale);
if(isset($child->vars['children']) && count($child->vars['children']))
{
$this->translate($child->vars['children'], $domain);
}
}
}
/**
* Returns the name of the type being extended.
*
* @return string The name of the type being extended
*/
public function getExtendedType()
{
return FormType::class;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment