TranslatableChoiceType.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. class TranslatableChoiceType extends ChoiceType
  18. {
  19. protected $translator;
  20. /**
  21. * @param \Symfony\Component\Translation\TranslatorInterface $translator
  22. */
  23. public function __construct(TranslatorInterface $translator)
  24. {
  25. $this->translator = $translator;
  26. }
  27. /**
  28. * @param array $options
  29. * @return array
  30. */
  31. public function getDefaultOptions(array $options)
  32. {
  33. $multiple = isset($options['multiple']) && $options['multiple'];
  34. $expanded = isset($options['expanded']) && $options['expanded'];
  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' => $multiple || $expanded ? array() : '',
  43. 'empty_value' => $multiple || $expanded || !isset($options['empty_value']) ? null : '',
  44. 'error_bubbling' => false,
  45. );
  46. }
  47. public function buildForm(FormBuilder $builder, array $options)
  48. {
  49. // translate options before building form
  50. foreach ($options['choices'] as $name => $value) {
  51. $options['choices'][$name] = $this->translator->trans($value, array(), $options['catalogue']);
  52. }
  53. // translate empty value
  54. if (!empty($options['empty_value'])) {
  55. $options['empty_value'] = $this->translator->trans($options['empty_value'], array(), $options['catalogue']);
  56. }
  57. parent::buildForm($builder, $options);
  58. }
  59. }