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