ModelType.php 2.5 KB

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