ModelType.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\FormBuilder;
  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\Form\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. public function buildForm(FormBuilder $builder, array $options)
  27. {
  28. if ($options['multiple']) {
  29. $builder
  30. ->addEventSubscriber(new MergeCollectionListener($options['model_manager']))
  31. ->prependClientTransformer(new ModelsToArrayTransformer($options['choice_list']));
  32. } else {
  33. $builder->prependClientTransformer(new ModelToIdTransformer($options['model_manager'], $options['class']));
  34. }
  35. }
  36. public function getDefaultOptions()
  37. {
  38. $options = array(
  39. 'template' => 'choice',
  40. 'multiple' => false,
  41. 'expanded' => false,
  42. 'model_manager' => null,
  43. 'class' => null,
  44. 'property' => null,
  45. 'query' => null,
  46. 'choices' => null,
  47. 'parent' => 'choice',
  48. 'preferred_choices' => array(),
  49. 'choice_list' => function (Options $options, $previousValue) {
  50. if ($previousValue instanceof ChoiceListInterface
  51. && count($choices = $previousValue->getChoices())) {
  52. return $choices;
  53. }
  54. return new ModelChoiceList(
  55. $options['model_manager'],
  56. $options['class'],
  57. $options['property'],
  58. $options['query'],
  59. $options['choices']
  60. );
  61. }
  62. );
  63. return $options;
  64. }
  65. public function getParent(array $options)
  66. {
  67. return isset($options['parent']) ? $options['parent'] : 'choice';
  68. }
  69. public function getName()
  70. {
  71. return 'sonata_type_model';
  72. }
  73. }