Last active
May 26, 2017 06:31
-
-
Save Slavenin/40ca0da8bfb5dbdc5d4da7ef38015887 to your computer and use it in GitHub Desktop.
Symfony form extrension translator on createView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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