AdminType.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\AbstractType;
  13. use Symfony\Component\Form\FormBuilderInterface;
  14. use Symfony\Component\OptionsResolver\OptionsResolverInterface;
  15. use Sonata\AdminBundle\Form\DataTransformer\ArrayToModelTransformer;
  16. class AdminType extends AbstractType
  17. {
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function buildForm(FormBuilderInterface $builder, array $options)
  22. {
  23. $admin = $this->getAdmin($options);
  24. if ($options['delete'] && $admin->isGranted('DELETE') ) {
  25. $builder->add('_delete', 'checkbox', array('required' => false, 'mapped' => false));
  26. }
  27. if (!$admin->hasSubject()) {
  28. $admin->setSubject($builder->getData());
  29. }
  30. $admin->defineFormBuilder($builder);
  31. $builder->addModelTransformer(new ArrayToModelTransformer($admin->getModelManager(), $admin->getClass()));
  32. }
  33. /**
  34. * {@inheritDoc}
  35. */
  36. public function setDefaultOptions(OptionsResolverInterface $resolver)
  37. {
  38. $resolver->setDefaults(array(
  39. 'delete' => true,
  40. 'auto_initialize' => false
  41. ));
  42. }
  43. /**
  44. * @param array $options
  45. *
  46. * @return \Sonata\AdminBundle\Admin\FieldDescriptionInterface
  47. *
  48. * @throws \RuntimeException
  49. */
  50. protected function getFieldDescription(array $options)
  51. {
  52. if (!isset($options['sonata_field_description'])) {
  53. throw new \RuntimeException('Please provide a valid `sonata_field_description` option');
  54. }
  55. return $options['sonata_field_description'];
  56. }
  57. /**
  58. * @param array $options
  59. *
  60. * @return \Sonata\AdminBundle\Admin\AdminInterface
  61. */
  62. protected function getAdmin(array $options)
  63. {
  64. return $this->getFieldDescription($options)->getAssociationAdmin();
  65. }
  66. /**
  67. * {@inheritDoc}
  68. */
  69. public function getName()
  70. {
  71. return 'sonata_type_admin';
  72. }
  73. }