TranslatableChoiceType.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. parent::buildForm($builder, $options);
  50. $builder->setAttribute('catalogue', $options['catalogue']);
  51. }
  52. public function buildView(FormView $view, FormInterface $form)
  53. {
  54. parent::buildView($view, $form);
  55. $choices = array();
  56. $catalogue = $form->getAttribute('catalogue');
  57. foreach ($view->get('choices') as $name => $value) {
  58. $choices[$name] = $this->translator->trans($value, array(), $catalogue);
  59. }
  60. $view->set('choices', $choices);
  61. }
  62. }