TranslatableChoiceType.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Form\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. * @return array
  31. */
  32. public function getDefaultOptions()
  33. {
  34. return array(
  35. 'multiple' => false,
  36. 'expanded' => false,
  37. 'choice_list' => null,
  38. 'choices' => array(),
  39. 'preferred_choices' => array(),
  40. 'catalogue' => 'messages',
  41. 'empty_data' => function (Options $options, $previousValue) {
  42. $multiple = isset($options['multiple']) && $options['multiple'];
  43. $expanded = isset($options['expanded']) && $options['expanded'];
  44. return $multiple || $expanded ? array() : '';
  45. },
  46. 'empty_value' => function (Options $options, $previousValue) {
  47. $multiple = isset($options['multiple']) && $options['multiple'];
  48. $expanded = isset($options['expanded']) && $options['expanded'];
  49. return $multiple || $expanded || !isset($options['empty_value']) ? null : '';
  50. },
  51. 'error_bubbling' => false,
  52. );
  53. }
  54. public function buildForm(FormBuilder $builder, array $options)
  55. {
  56. // translate options before building form
  57. foreach ($options['choices'] as $name => $value) {
  58. $options['choices'][$name] = $this->translator->trans($value, array(), $options['catalogue']);
  59. }
  60. // translate empty value
  61. if (!empty($options['empty_value'])) {
  62. $options['empty_value'] = $this->translator->trans($options['empty_value'], array(), $options['catalogue']);
  63. }
  64. parent::buildForm($builder, $options);
  65. }
  66. }