TranslatableChoiceType.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. *
  10. */
  11. namespace Sonata\AdminBundle\Form\Type;
  12. use Symfony\Component\Translation\TranslatorInterface;
  13. use Symfony\Component\Form\AbstractType;
  14. use Symfony\Component\Form\FormInterface;
  15. use Symfony\Component\Form\FormView;
  16. use Symfony\Component\Form\FormBuilderInterface;
  17. use Symfony\Component\OptionsResolver\Options;
  18. use Symfony\Component\OptionsResolver\OptionsResolverInterface;
  19. class TranslatableChoiceType extends AbstractType
  20. {
  21. protected $translator;
  22. /**
  23. * @param \Symfony\Component\Translation\TranslatorInterface $translator
  24. */
  25. public function __construct(TranslatorInterface $translator)
  26. {
  27. $this->translator = $translator;
  28. }
  29. /**
  30. * {@inheritDoc}
  31. */
  32. public function setDefaultOptions(OptionsResolverInterface $resolver)
  33. {
  34. $resolver->setDefaults(array(
  35. 'catalogue' => 'messages',
  36. ));
  37. }
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function buildView(FormView $view, FormInterface $form, array $options)
  42. {
  43. // translate options before building form
  44. foreach ($view->vars['choices'] as $choiceView) {
  45. $choiceView->label = $this->translator->trans($choiceView->label, array(), $options['catalogue']);
  46. }
  47. // translate preferred options
  48. foreach ($view->vars['preferred_choices'] as $choiceView) {
  49. $choiceView->label = $this->translator->trans($choiceView->label, array(), $options['catalogue']);
  50. }
  51. // translate empty value
  52. if (!empty($view->vars['empty_value'])) {
  53. $view->vars['empty_value'] = $this->translator->trans($view->vars['empty_value'], array(), $options['catalogue']);
  54. }
  55. $view->vars['translation_domain'] = $options['catalogue'];
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public function getParent()
  61. {
  62. return 'choice';
  63. }
  64. /**
  65. * {@inheritDoc}
  66. */
  67. public function getName()
  68. {
  69. return 'sonata_type_translatable_choice';
  70. }
  71. }