FormBuilder.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. namespace Sonata\BaseApplicationBundle\Builder;
  11. use Sonata\BaseApplicationBundle\Form\ValueTransformer\EntityToIDTransformer;
  12. use Sonata\BaseApplicationBundle\Form\ValueTransformer\ArrayToObjectTransformer;
  13. use Sonata\BaseApplicationBundle\Form\EditableCollectionField;
  14. use Sonata\BaseApplicationBundle\Form\EditableFieldGroup;
  15. use Sonata\BaseApplicationBundle\Admin\FieldDescription;
  16. use Sonata\BaseApplicationBundle\Admin\Admin;
  17. use Symfony\Component\Form\Form;
  18. use Symfony\Component\Form\FormInterface;
  19. use Symfony\Component\Form\FormContextInterface;
  20. use Symfony\Component\Validator\ValidatorInterface;
  21. use Symfony\Component\Form\FieldFactory\FieldFactoryInterface;
  22. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  23. class FormBuilder implements FormBuilderInterface
  24. {
  25. protected $fieldFactory;
  26. protected $formContext;
  27. protected $validator;
  28. public function __construct(FieldFactoryInterface $fieldFactory, FormContextInterface $formContext, ValidatorInterface $validator)
  29. {
  30. $this->fieldFactory = $fieldFactory;
  31. $this->formContext = $formContext;
  32. $this->validator = $validator;
  33. }
  34. /**
  35. * todo: put this in the DIC
  36. *
  37. * built-in definition
  38. *
  39. * @var array
  40. */
  41. protected $formFieldClasses = array(
  42. 'string' => 'Symfony\\Component\\Form\\TextField',
  43. 'text' => 'Symfony\\Component\\Form\\TextareaField',
  44. 'boolean' => 'Symfony\\Component\\Form\\CheckboxField',
  45. 'integer' => 'Symfony\\Component\\Form\\IntegerField',
  46. 'tinyint' => 'Symfony\\Component\\Form\\IntegerField',
  47. 'smallint' => 'Symfony\\Component\\Form\\IntegerField',
  48. 'mediumint' => 'Symfony\\Component\\Form\\IntegerField',
  49. 'bigint' => 'Symfony\\Component\\Form\\IntegerField',
  50. 'decimal' => 'Symfony\\Component\\Form\\NumberField',
  51. 'datetime' => 'Symfony\\Component\\Form\\DateTimeField',
  52. 'date' => 'Symfony\\Component\\Form\\DateField',
  53. 'choice' => 'Symfony\\Component\\Form\\ChoiceField',
  54. 'array' => 'Symfony\\Component\\Form\\FieldGroup',
  55. 'country' => 'Symfony\\Component\\Form\\CountryField',
  56. );
  57. /**
  58. * return the field associated to a FieldDescription
  59. * ie : build the embedded form from the related Admin instance
  60. *
  61. * @throws RuntimeException
  62. * @param $object
  63. * @param FieldDescription $fieldDescription
  64. * @param null $fieldName
  65. * @return FieldGroup
  66. */
  67. protected function getRelatedAssociatedField($object, FieldDescription $fieldDescription, $fieldName = null)
  68. {
  69. $fieldName = $fieldName ?: $fieldDescription->getFieldName();
  70. $associatedAdmin = $fieldDescription->getAssociationAdmin();
  71. if (!$associatedAdmin) {
  72. throw new \RuntimeException(sprintf('inline mode for field `%s` required an Admin definition', $fieldName));
  73. }
  74. // retrieve the related object
  75. $targetObject = $associatedAdmin->getNewInstance();
  76. // retrieve the related form
  77. $targetForm = $associatedAdmin->getForm($targetObject);
  78. // create the transformer
  79. $transformer = new ArrayToObjectTransformer(array(
  80. 'em' => $fieldDescription->getAdmin()->getEntityManager(),
  81. 'className' => $fieldDescription->getTargetEntity()
  82. ));
  83. // create the "embedded" field
  84. if ($fieldDescription->getType() == ClassMetadataInfo::ONE_TO_MANY) {
  85. $field = new EditableFieldGroup($fieldName, array(
  86. 'value_transformer' => $transformer,
  87. ));
  88. } else {
  89. $field = new \Symfony\Component\Form\Form($fieldName, array(
  90. 'value_transformer' => $transformer,
  91. ));
  92. }
  93. foreach ($targetForm->getFields() as $name => $formField) {
  94. if ($name == '_token') {
  95. continue;
  96. }
  97. $field->add($formField);
  98. }
  99. return $field;
  100. }
  101. /**
  102. * return the class associated to a FieldDescription if any defined
  103. *
  104. * @throws RuntimeException
  105. * @param FieldDescription $fieldDescription
  106. * @return bool|string
  107. */
  108. public function getFormFieldClass(FieldDescription $fieldDescription)
  109. {
  110. $class = false;
  111. // the user redefined the mapping type, use the default built in definition
  112. if (!$fieldDescription->getFieldMapping() || $fieldDescription->getType() != $fieldDescription->getMappingType()) {
  113. $class = array_key_exists($fieldDescription->getType(), $this->formFieldClasses) ? $this->formFieldClasses[$fieldDescription->getType()] : false;
  114. } else if($fieldDescription->getOption('form_field_widget', false)) {
  115. $class = $fieldDescription->getOption('form_field_widget', false);
  116. }
  117. if ($class && !class_exists($class)) {
  118. throw new \RuntimeException(sprintf('The class `%s` does not exist for field `%s`', $class, $fieldDescription->getType()));
  119. }
  120. return $class;
  121. }
  122. /**
  123. * Add a new instance to the related FieldDescription value
  124. *
  125. * @param $object
  126. * @param FieldDescription $fieldDescription
  127. * @return void
  128. */
  129. public function addNewInstance($object, FieldDescription $fieldDescription)
  130. {
  131. $instance = $fieldDescription->getAssociationAdmin()->getNewInstance();
  132. $mapping = $fieldDescription->getAssociationMapping();
  133. $method = sprintf('add%s', FieldDescription::camelize($mapping['fieldName']));
  134. $object->$method($instance);
  135. }
  136. /**
  137. * return an OneToOne associated field
  138. *
  139. * @param $object
  140. * @param FieldDescription $fieldDescription
  141. * @return ChoiceField
  142. */
  143. protected function getOneToOneField($object, FieldDescription $fieldDescription)
  144. {
  145. // tweak the widget depend on the edit mode
  146. if ($fieldDescription->getOption('edit') == 'inline') {
  147. return $this->getRelatedAssociatedField($object, $fieldDescription);
  148. }
  149. // TODO : remove this once an EntityField will be available
  150. $options = array(
  151. 'value_transformer' => new EntityToIDTransformer(array(
  152. 'em' => $fieldDescription->getAdmin()->getEntityManager(),
  153. 'className' => $fieldDescription->getTargetEntity()
  154. ))
  155. );
  156. $options = array_merge($options, $fieldDescription->getOption('form_field_options', array()));
  157. if ($fieldDescription->getOption('edit') == 'list') {
  158. return new \Symfony\Component\Form\TextField($fieldDescription->getFieldName(), $options);
  159. }
  160. $class = $fieldDescription->getOption('form_field_widget', false);
  161. // set valid default value
  162. if (!$class) {
  163. $instance = $this->getFieldFactory()->getInstance(
  164. $fieldDescription->getAdmin()->getClass(),
  165. $fieldDescription->getFieldName(),
  166. $fieldDescription->getOption('form_field_options', array())
  167. );
  168. } else {
  169. $instance = new $class($fieldDescription->getFieldName(), $options);
  170. }
  171. return $instance;
  172. }
  173. /**
  174. * return the OneToMany associated field
  175. *
  176. * @param $object
  177. * @param FieldDescription $fieldDescription
  178. * @return ChoiceField|CollectionField
  179. */
  180. protected function getOneToManyField($object, FieldDescription $fieldDescription)
  181. {
  182. if ($fieldDescription->getOption('edit') == 'inline') {
  183. $prototype = $this->getRelatedAssociatedField($object, $fieldDescription);
  184. $value = $fieldDescription->getValue($object);
  185. // add new instances if the min number is not matched
  186. if ($fieldDescription->getOption('min', 0) > count($value)) {
  187. $diff = $fieldDescription->getOption('min', 0) - count($value);
  188. foreach (range(1, $diff) as $i) {
  189. $this->addNewInstance($object, $fieldDescription);
  190. }
  191. }
  192. // use custom one to expose the newfield method
  193. return new \Sonata\BaseApplicationBundle\Form\EditableCollectionField($prototype);
  194. }
  195. return $this->getManyToManyField($object, $fieldDescription);
  196. }
  197. protected function getManyToManyField($object, FieldDescription $fieldDescription)
  198. {
  199. $class = $fieldDescription->getOption('form_field_widget', false);
  200. // set valid default value
  201. if (!$class) {
  202. $instance = $this->getFieldFactory()->getInstance(
  203. $fieldDescription->getAdmin()->getClass(),
  204. $fieldDescription->getFieldName(),
  205. $fieldDescription->getOption('form_field_options', array())
  206. );
  207. } else {
  208. $instance = new $class(
  209. $fieldDescription->getFieldName(),
  210. $fieldDescription->getOption('form_field_options', array())
  211. );
  212. }
  213. return $instance;
  214. }
  215. protected function getManyToOneField($object, FieldDescription $fieldDescription)
  216. {
  217. // tweak the widget depend on the edit mode
  218. if ($fieldDescription->getOption('edit') == 'inline') {
  219. return $this->getRelatedAssociatedField($object, $fieldDescription);
  220. }
  221. $options = array(
  222. 'value_transformer' => new EntityToIDTransformer(array(
  223. 'em' => $fieldDescription->getAdmin()->getEntityManager(),
  224. 'className' => $fieldDescription->getTargetEntity()
  225. ))
  226. );
  227. $options = array_merge($options, $fieldDescription->getOption('form_field_options', array()));
  228. if ($fieldDescription->getOption('edit') == 'list') {
  229. return new \Symfony\Component\Form\TextField($fieldDescription->getFieldName(), $options);
  230. }
  231. $class = $fieldDescription->getOption('form_field_widget', false);
  232. if (!$class) {
  233. $instance = $this->getFieldFactory()->getInstance(
  234. $fieldDescription->getAdmin()->getClass(),
  235. $fieldDescription->getFieldName(),
  236. $fieldDescription->getOption('form_field_options', array())
  237. );
  238. } else {
  239. $instance = new $class($fieldDescription->getFieldName(), array_merge(array('expanded' => true), $options));
  240. }
  241. return $instance;
  242. }
  243. /**
  244. * The method add a new field to the provided Form, there are 4 ways to add new field :
  245. *
  246. * - if $name is a string with no related FieldDescription, then the form will use the FieldFactory
  247. * to instantiate a new Field
  248. * - if $name is a FormDescription, the method uses information defined in the FormDescription to
  249. * instantiate a new Field
  250. * - if $name is a FieldInterface, then a FieldDescription is created, the FieldInterface is added to
  251. * the form
  252. * - if $name is a string with a related FieldDescription, then the method uses information defined in the
  253. * FormDescription to instantiate a new Field
  254. *
  255. *
  256. * @param Form $form
  257. * @param FieldDescription $name
  258. * @param array $options
  259. * @return void
  260. */
  261. public function addField(Form $form, FieldDescription $fieldDescription)
  262. {
  263. switch ($fieldDescription->getType()) {
  264. case ClassMetadataInfo::ONE_TO_MANY:
  265. $field = $this->getOneToManyField($form->getData(), $fieldDescription);
  266. break;
  267. case ClassMetadataInfo::MANY_TO_MANY:
  268. $field = $this->getManyToManyField($form->getData(), $fieldDescription);
  269. break;
  270. case ClassMetadataInfo::MANY_TO_ONE:
  271. $field = $this->getManyToOneField($form->getData(), $fieldDescription);
  272. break;
  273. case ClassMetadataInfo::ONE_TO_ONE:
  274. $field = $this->getOneToOneField($form->getData(), $fieldDescription);
  275. break;
  276. default:
  277. $class = $this->getFormFieldClass($fieldDescription);
  278. // there is no way to use a custom widget with the FieldFactory
  279. if($class) {
  280. $field = new $class(
  281. $fieldDescription->getFieldName(),
  282. $fieldDescription->getOption('form_field_options', array())
  283. );
  284. } else {
  285. $field = $this->getFieldFactory()->getInstance(
  286. $fieldDescription->getAdmin()->getClass(),
  287. $fieldDescription->getFieldName(),
  288. $fieldDescription->getOption('form_field_options', array())
  289. );
  290. }
  291. }
  292. return $form->add($field);
  293. }
  294. /**
  295. * The method define the correct default settings for the provided FieldDescription
  296. *
  297. * @param FieldDescription $fieldDescription
  298. * @return void
  299. */
  300. public function fixFieldDescription(Admin $admin, FieldDescription $fieldDescription, array $options = array())
  301. {
  302. $fieldDescription->mergeOptions($options);
  303. // set the default field mapping
  304. if (isset($admin->getClassMetaData()->fieldMappings[$fieldDescription->getName()])) {
  305. $fieldDescription->setFieldMapping($admin->getClassMetaData()->fieldMappings[$fieldDescription->getName()]);
  306. }
  307. // set the default association mapping
  308. if (isset($admin->getClassMetaData()->associationMappings[$fieldDescription->getName()])) {
  309. $fieldDescription->setAssociationMapping($admin->getClassMetaData()->associationMappings[$fieldDescription->getName()]);
  310. }
  311. if(!$fieldDescription->getType()) {
  312. throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), get_class($admin)));
  313. }
  314. $fieldDescription->setAdmin($admin);
  315. $fieldDescription->setOption('edit', $fieldDescription->getOption('edit', 'standard'));
  316. // fix template value for doctrine association fields
  317. if (!$fieldDescription->getTemplate()) {
  318. $fieldDescription->setTemplate(sprintf('SonataBaseApplicationBundle:CRUD:edit_%s.html.twig', $fieldDescription->getType()));
  319. }
  320. if ($fieldDescription->getType() == ClassMetadataInfo::ONE_TO_ONE) {
  321. $fieldDescription->setTemplate('SonataBaseApplicationBundle:CRUD:edit_one_to_one.html.twig');
  322. $admin->attachAdminClass($fieldDescription);
  323. }
  324. if ($fieldDescription->getType() == ClassMetadataInfo::MANY_TO_ONE) {
  325. $fieldDescription->setTemplate('SonataBaseApplicationBundle:CRUD:edit_many_to_one.html.twig');
  326. $admin->attachAdminClass($fieldDescription);
  327. }
  328. if ($fieldDescription->getType() == ClassMetadataInfo::MANY_TO_MANY) {
  329. $fieldDescription->setTemplate('SonataBaseApplicationBundle:CRUD:edit_many_to_many.html.twig');
  330. $admin->attachAdminClass($fieldDescription);
  331. }
  332. if ($fieldDescription->getType() == ClassMetadataInfo::ONE_TO_MANY) {
  333. $fieldDescription->setTemplate('SonataBaseApplicationBundle:CRUD:edit_one_to_many.html.twig');
  334. if($fieldDescription->getOption('edit') == 'inline' && !$fieldDescription->getOption('widget_form_field')) {
  335. $fieldDescription->setOption('widget_form_field', 'Bundle\\Sonata\\BaseApplicationBundle\\Form\\EditableFieldGroup');
  336. }
  337. $admin->attachAdminClass($fieldDescription);
  338. }
  339. // set correct default value
  340. if ($fieldDescription->getType() == 'datetime') {
  341. $options = $fieldDescription->getOption('form_field_options', array());
  342. if (!isset($options['years'])) {
  343. $options['years'] = range(1900, 2100);
  344. }
  345. $fieldDescription->setOption('form_field', $options);
  346. }
  347. }
  348. public function setFieldFactory($fieldFactory)
  349. {
  350. $this->fieldFactory = $fieldFactory;
  351. }
  352. public function getFieldFactory()
  353. {
  354. return $this->fieldFactory;
  355. }
  356. public function setFormContext($formContext)
  357. {
  358. $this->formContext = $formContext;
  359. }
  360. public function getFormContext()
  361. {
  362. return $this->formContext;
  363. }
  364. public function setFormFieldClasses(array $formFieldClasses)
  365. {
  366. $this->formFieldClasses = $formFieldClasses;
  367. }
  368. public function getFormFieldClasses()
  369. {
  370. return $this->formFieldClasses;
  371. }
  372. public function getBaseForm($name, $object, array $options = array())
  373. {
  374. return new Form($name, array_merge(array(
  375. 'data' => $object,
  376. 'validator' => $this->getValidator(),
  377. 'context' => $this->getFormContext(),
  378. ), $options));
  379. }
  380. public function setValidator($validator)
  381. {
  382. $this->validator = $validator;
  383. }
  384. public function getValidator()
  385. {
  386. return $this->validator;
  387. }
  388. }