TranslatableChoiceType.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  56. /**
  57. * {@inheritDoc}
  58. */
  59. public function getParent()
  60. {
  61. return 'choice';
  62. }
  63. /**
  64. * {@inheritDoc}
  65. */
  66. public function getName()
  67. {
  68. return 'sonata_type_translatable_choice';
  69. }
  70. }