ModelType.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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\Form\Extension\Core\ChoiceList\ChoiceListInterface;
  13. use Symfony\Component\Form\FormBuilderInterface;
  14. use Symfony\Component\Form\FormFactoryInterface;
  15. use Symfony\Component\Form\AbstractType;
  16. use Symfony\Component\Form\FormInterface;
  17. use Symfony\Component\Form\FormView;
  18. use Symfony\Component\OptionsResolver\Options;
  19. use Sonata\AdminBundle\Form\EventListener\MergeCollectionListener;
  20. use Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList;
  21. use Sonata\AdminBundle\Form\DataTransformer\ModelsToArrayTransformer;
  22. use Sonata\AdminBundle\Form\DataTransformer\ModelToIdTransformer;
  23. use Sonata\AdminBundle\Model\ModelManagerInterface;
  24. class ModelType extends AbstractType
  25. {
  26. /**
  27. * {@inheritDoc}
  28. */
  29. public function buildForm(FormBuilderInterface $builder, array $options)
  30. {
  31. if ($options['multiple']) {
  32. $builder
  33. ->addEventSubscriber(new MergeCollectionListener($options['model_manager']))
  34. ->prependClientTransformer(new ModelsToArrayTransformer($options['choice_list']));
  35. } else {
  36. $builder->prependClientTransformer(new ModelToIdTransformer($options['model_manager'], $options['class']));
  37. }
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function getDefaultOptions()
  43. {
  44. $options = array(
  45. 'template' => 'choice',
  46. 'multiple' => false,
  47. 'expanded' => false,
  48. 'model_manager' => null,
  49. 'class' => null,
  50. 'property' => null,
  51. 'query' => null,
  52. 'choices' => null,
  53. 'parent' => 'choice',
  54. 'preferred_choices' => array(),
  55. 'choice_list' => function (Options $options, $previousValue) {
  56. if ($previousValue instanceof ChoiceListInterface
  57. && count($choices = $previousValue->getChoices())) {
  58. return $choices;
  59. }
  60. return new ModelChoiceList(
  61. $options['model_manager'],
  62. $options['class'],
  63. $options['property'],
  64. $options['query'],
  65. $options['choices']
  66. );
  67. }
  68. );
  69. return $options;
  70. }
  71. /**
  72. * {@inheritDoc}
  73. */
  74. public function getParent(array $options)
  75. {
  76. return isset($options['parent']) ? $options['parent'] : 'choice';
  77. }
  78. /**
  79. * {@inheritDoc}
  80. */
  81. public function getName()
  82. {
  83. return 'sonata_type_model';
  84. }
  85. }