ModelType.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. public function buildForm(FormBuilder $builder, array $options)
  23. {
  24. if ($options['multiple']) {
  25. $builder
  26. ->addEventSubscriber(new MergeCollectionListener($this->modelManager))
  27. ->prependClientTransformer(new ModelsToArrayTransformer($options['choice_list']));
  28. } else {
  29. $builder->prependClientTransformer(new ModelToIdTransformer($this->modelManager, $options['class']));
  30. }
  31. }
  32. public function getDefaultOptions(array $options)
  33. {
  34. $defaultOptions = array(
  35. 'template' => 'choice',
  36. 'multiple' => false,
  37. 'expanded' => false,
  38. 'model_manager' => null,
  39. 'class' => null,
  40. 'property' => null,
  41. 'query' => null,
  42. 'choices' => array(),
  43. 'parent' => 'choice',
  44. 'preferred_choices' => array(),
  45. 'field_description' => false,
  46. );
  47. $options = array_replace($defaultOptions, $options);
  48. if (!isset($options['choice_list'])) {
  49. $defaultOptions['choice_list'] = new ModelChoiceList(
  50. $options['model_manager'],
  51. $options['class'],
  52. $options['property'],
  53. $options['query'],
  54. $options['choices']
  55. );
  56. }
  57. return $defaultOptions;
  58. }
  59. public function getParent(array $options)
  60. {
  61. return $options['parent'];
  62. }
  63. public function getName()
  64. {
  65. return 'sonata_model';
  66. }
  67. }