TranslatableChoiceType.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\Extension\Core\Type\ChoiceType;
  14. use Symfony\Component\Form\FormInterface;
  15. use Symfony\Component\Form\FormView;
  16. use Symfony\Component\Form\FormBuilder;
  17. use Symfony\Component\OptionsResolver\Options;
  18. class TranslatableChoiceType extends ChoiceType
  19. {
  20. protected $translator;
  21. /**
  22. * @param \Symfony\Component\Translation\TranslatorInterface $translator
  23. */
  24. public function __construct(TranslatorInterface $translator)
  25. {
  26. $this->translator = $translator;
  27. }
  28. /**
  29. * @param array $options
  30. *
  31. * @return array
  32. */
  33. public function getDefaultOptions()
  34. {
  35. return array(
  36. 'multiple' => false,
  37. 'expanded' => false,
  38. 'choice_list' => null,
  39. 'choices' => array(),
  40. 'preferred_choices' => array(),
  41. 'catalogue' => 'messages',
  42. 'empty_data' => function (Options $options, $previousValue) {
  43. $multiple = isset($options['multiple']) && $options['multiple'];
  44. $expanded = isset($options['expanded']) && $options['expanded'];
  45. return $multiple || $expanded ? array() : '';
  46. },
  47. 'empty_value' => function (Options $options, $previousValue) {
  48. $multiple = isset($options['multiple']) && $options['multiple'];
  49. $expanded = isset($options['expanded']) && $options['expanded'];
  50. return $multiple || $expanded || !isset($options['empty_value']) ? null : '';
  51. },
  52. 'error_bubbling' => false,
  53. );
  54. }
  55. public function buildForm(FormBuilder $builder, array $options)
  56. {
  57. // translate options before building form
  58. foreach ($options['choices'] as $name => $value) {
  59. $options['choices'][$name] = $this->translator->trans($value, array(), $options['catalogue']);
  60. }
  61. // translate empty value
  62. if (!empty($options['empty_value'])) {
  63. $options['empty_value'] = $this->translator->trans($options['empty_value'], array(), $options['catalogue']);
  64. }
  65. parent::buildForm($builder, $options);
  66. }
  67. }