ModelType.php 2.4 KB

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