Admin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 Bundle\BaseApplicationBundle\Admin;
  11. use Symfony\Component\DependencyInjection\ContainerAware;
  12. use Symfony\Component\Form\Form;
  13. abstract class Admin extends ContainerAware
  14. {
  15. protected $class;
  16. protected $list_fields = false;
  17. protected $form_fields = false;
  18. protected $filter_fields = array(); // by default there is no filter
  19. protected $filter_datagrid;
  20. protected $base_route = '';
  21. protected $base_controller_name;
  22. // note : don't like this, but havn't find a better way to do it
  23. protected $configuration_pool;
  24. protected $code;
  25. protected $label;
  26. public function configure()
  27. {
  28. $this->buildFormFields();
  29. $this->buildListFields();
  30. }
  31. public function getClass()
  32. {
  33. return $this->class;
  34. }
  35. public function getEntityManager()
  36. {
  37. return $this->container->get('doctrine.orm.default_entity_manager');
  38. }
  39. public function getClassMetaData()
  40. {
  41. $em = $this->getEntityManager();
  42. return $em->getClassMetaData($this->getClass());
  43. }
  44. public function getBatchActions()
  45. {
  46. return array(
  47. 'delete' => 'action_delete'
  48. );
  49. }
  50. public function getUrls()
  51. {
  52. return array(
  53. 'list' => array(
  54. 'url' => $this->base_route.'_list',
  55. 'params' => array(),
  56. ),
  57. 'create' => array(
  58. 'url' => $this->base_route.'_create',
  59. 'params' => array(),
  60. ),
  61. 'update' => array(
  62. 'url' => $this->base_route.'_update',
  63. 'params' => array()
  64. ),
  65. 'delete' => array(
  66. 'url' => $this->base_route.'_delete',
  67. 'params' => array()
  68. ),
  69. 'edit' => array(
  70. 'url' => $this->base_route.'_edit',
  71. 'params' => array()
  72. ),
  73. 'batch' => array(
  74. 'url' => $this->base_route.'_batch',
  75. 'params' => array()
  76. )
  77. );
  78. }
  79. public function getUrl($name)
  80. {
  81. $urls = $this->getUrls();
  82. if(!isset($urls[$name])) {
  83. return false;
  84. }
  85. return $urls[$name];
  86. }
  87. public function generateUrl($name, $params = array())
  88. {
  89. $url = $this->getUrl($name);
  90. if(!$url) {
  91. throw new \RuntimeException(sprintf('unable to find the url `%s`', $name));
  92. }
  93. if(!is_array($params)) {
  94. $params = array();
  95. }
  96. return $this->container->get('router')->generate($url['url'], array_merge($url['params'], $params));
  97. }
  98. public function getListTemplate()
  99. {
  100. return 'BaseApplicationBundle:CRUD:list.twig';
  101. }
  102. public function getEditTemplate()
  103. {
  104. return 'BaseApplicationBundle:CRUD:edit.twig';
  105. }
  106. public function getReflectionFields()
  107. {
  108. return $this->getClassMetaData()->reflFields;
  109. }
  110. /**
  111. * make sure the base field are set in the correct format
  112. *
  113. * @param $selected_fields
  114. * @return array
  115. */
  116. static public function getBaseFields($metadata, $selected_fields)
  117. {
  118. // if nothing is defined we display all fields
  119. if(!$selected_fields) {
  120. $selected_fields = array_keys($metadata->reflFields) + array_keys($metadata->associationMappings);
  121. }
  122. // make sure we works with array
  123. foreach($selected_fields as $name => $options) {
  124. if(is_array($options)) {
  125. $fields[$name] = $options;
  126. } else {
  127. $fields[$options] = array();
  128. $name = $options;
  129. }
  130. if(isset($metadata->fieldMappings[$name])) {
  131. $fields[$name] = array_merge(
  132. $metadata->fieldMappings[$name],
  133. $fields[$name]
  134. );
  135. }
  136. if(isset($metadata->associationMappings[$name])) {
  137. $fields[$name] = array_merge(
  138. $metadata->associationMappings[$name],
  139. $fields[$name]
  140. );
  141. }
  142. if(isset($metadata->reflFields[$name])) {
  143. $fields[$name]['reflection'] =& $metadata->reflFields[$name];
  144. }
  145. }
  146. return $fields;
  147. }
  148. /**
  149. * @return void
  150. */
  151. public function configureFormFields()
  152. {
  153. }
  154. /**
  155. * return the target objet
  156. *
  157. * @param $id
  158. * @return
  159. */
  160. public function getObject($id)
  161. {
  162. return $this->getEntityManager()
  163. ->find($this->getClass(), $id);
  164. }
  165. /**
  166. * build the fields to use in the form
  167. *
  168. * @throws RuntimeException
  169. * @return
  170. */
  171. public function buildFormFields()
  172. {
  173. $this->form_fields = self::getBaseFields($this->getClassMetaData(), $this->form_fields);
  174. foreach($this->form_fields as $name => $options) {
  175. if(!isset($this->form_fields[$name]['type'])) {
  176. throw new \RuntimeException(sprintf('You must declare a type for the field `%s`', $name));
  177. }
  178. // make sure the options field is set
  179. if(!isset($this->form_fields[$name]['options'])) {
  180. $this->form_fields[$name]['options'] = array();
  181. }
  182. // fix template value for doctrine association fields
  183. if(!isset($this->form_fields[$name]['template']) && isset($this->form_fields[$name]['type'])) {
  184. $this->form_fields[$name]['template'] = sprintf('BaseApplicationBundle:CRUD:edit_%s.twig', $this->form_fields[$name]['type']);
  185. if($this->form_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::ONE_TO_ONE)
  186. {
  187. $this->form_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:edit_one_to_one.twig';
  188. }
  189. if($this->form_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_ONE)
  190. {
  191. $this->form_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:edit_many_to_one.twig';
  192. $this->form_fields[$name]['configuration'] = $this->getConfigurationPool()
  193. ->getConfigurationByClass($this->form_fields[$name]['targetEntity']);
  194. }
  195. if($this->form_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY)
  196. {
  197. $this->form_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:edit_many_to_many.twig';
  198. $this->form_fields[$name]['configuration'] = $this->getConfigurationPool()
  199. ->getConfigurationByClass($this->form_fields[$name]['targetEntity']);
  200. }
  201. }
  202. // set correct default value
  203. if($this->form_fields[$name]['type'] == 'datetime') {
  204. if(!isset($this->form_fields[$name]['options']['date_widget'])) {
  205. $this->form_fields[$name]['options']['date_widget'] = \Symfony\Component\Form\DateField::CHOICE;
  206. }
  207. if(!isset($this->form_fields[$name]['options']['years'])) {
  208. $this->form_fields[$name]['options']['years'] = range(1900, 2100);
  209. }
  210. }
  211. // unset the identifier field as it is not required to update an object
  212. if(isset($this->form_fields[$name]['id'])) {
  213. unset($this->form_fields[$name]);
  214. }
  215. }
  216. $this->configureFormFields();
  217. return $this->form_fields;
  218. }
  219. /**
  220. * build the field to use in the list view
  221. *
  222. * @return void
  223. */
  224. public function buildListFields()
  225. {
  226. $this->list_fields = self::getBaseFields($this->getClassMetaData(), $this->list_fields);
  227. foreach($this->list_fields as $name => $options) {
  228. $this->list_fields[$name]['code'] = $name;
  229. // set the label if none is set
  230. if(!isset($this->list_fields[$name]['label']))
  231. {
  232. $this->list_fields[$name]['label'] = $name;
  233. }
  234. // set the default type if none is set
  235. if(!isset($this->list_fields[$name]['type'])) {
  236. $this->list_fields[$name]['type'] = 'string';
  237. }
  238. // fix template for mapping
  239. if($this->list_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_ONE) {
  240. $this->list_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:list_many_to_one.twig';
  241. $this->list_fields[$name]['configuration'] = $this->getConfigurationPool()
  242. ->getConfigurationByClass($this->list_fields[$name]['targetEntity']);
  243. }
  244. if($this->list_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::ONE_TO_MANY) {
  245. $this->list_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:list_one_to_many.twig';
  246. }
  247. if($this->list_fields[$name]['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {
  248. $this->list_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:list_many_to_many.twig';
  249. }
  250. // define the default template
  251. if(!isset($this->list_fields[$name]['template'])) {
  252. $this->list_fields[$name]['template'] = sprintf('BaseApplicationBundle:CRUD:list_%s.twig', $this->list_fields[$name]['type']);
  253. }
  254. // define the default template for identifier field
  255. if(isset($this->list_fields[$name]['id'])) {
  256. $this->list_fields[$name]['template'] = 'BaseApplicationBundle:CRUD:list_identifier.twig';
  257. }
  258. }
  259. if(!isset($this->list_fields['_batch'])) {
  260. $this->list_fields = array('_batch' => array(
  261. 'code' => '_batch',
  262. 'template' => 'BaseApplicationBundle:CRUD:list__batch.twig',
  263. 'label' => 'batch',
  264. ) ) + $this->list_fields;
  265. }
  266. $this->configureListFields();
  267. return $this->list_fields;
  268. }
  269. public function configureListFields()
  270. {
  271. }
  272. public function configureFilterFields()
  273. {
  274. }
  275. public function getFilterDatagrid()
  276. {
  277. if(!$this->filter_datagrid) {
  278. $this->filter_datagrid = new \Bundle\BaseApplicationBundle\Tool\Datagrid($this->getClass(), $this->getEntityManager());
  279. $this->configureFilterFields();
  280. $this->filter_datagrid->setFilterFields($this->filter_fields);
  281. $this->filter_datagrid->buildFilterFields();
  282. }
  283. return $this->filter_datagrid;
  284. }
  285. /**
  286. * Construct and build the form field definitions
  287. *
  288. * @return list form field definition
  289. */
  290. public function getFormFields()
  291. {
  292. return $this->form_fields;
  293. }
  294. public function getListFields()
  295. {
  296. return $this->list_fields;
  297. }
  298. public function getChoices($description)
  299. {
  300. $targets = $this->getEntityManager()
  301. ->createQueryBuilder()
  302. ->select('t')
  303. ->from($description['targetEntity'], 't')
  304. ->getQuery()
  305. ->execute();
  306. $choices = array();
  307. foreach($targets as $target) {
  308. // todo : puts this into a configuration option and use reflection
  309. foreach(array('getTitle', 'getName', '__toString') as $getter) {
  310. if(method_exists($target, $getter)) {
  311. $choices[$target->getId()] = $target->$getter();
  312. break;
  313. }
  314. }
  315. }
  316. return $choices;
  317. }
  318. public function getForm($object, $fields)
  319. {
  320. $this->container->get('session')->start();
  321. $form = new Form('data', $object, $this->container->get('validator'));
  322. foreach($fields as $name => $description) {
  323. if(!isset($description['type'])) {
  324. continue;
  325. }
  326. switch($description['type']) {
  327. case \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY:
  328. $transformer = new \Symfony\Bundle\DoctrineBundle\Form\ValueTransformer\CollectionToChoiceTransformer(array(
  329. 'em' => $this->getEntityManager(),
  330. 'className' => $description['targetEntity']
  331. ));
  332. $field = new \Symfony\Component\Form\ChoiceField($name, array_merge(array(
  333. 'expanded' => true,
  334. 'multiple' => true,
  335. 'choices' => $this->getChoices($description),
  336. 'value_transformer' => $transformer,
  337. ), $description['options']));
  338. break;
  339. case \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_ONE:
  340. case \Doctrine\ORM\Mapping\ClassMetadataInfo::ONE_TO_ONE:
  341. $transformer = new \Symfony\Bundle\DoctrineBundle\Form\ValueTransformer\EntityToIDTransformer(array(
  342. 'em' => $this->getEntityManager(),
  343. 'className' => $description['targetEntity']
  344. ));
  345. $field = new \Symfony\Component\Form\ChoiceField($name, array_merge(array(
  346. 'expanded' => false,
  347. 'choices' => $this->getChoices($description),
  348. 'value_transformer' => $transformer,
  349. ), $description['options']));
  350. break;
  351. case 'string':
  352. $field = new \Symfony\Component\Form\TextField($name, $description['options']);
  353. break;
  354. case 'text':
  355. $field = new \Symfony\Component\Form\TextareaField($name, $description['options']);
  356. break;
  357. case 'boolean':
  358. $field = new \Symfony\Component\Form\CheckboxField($name, $description['options']);
  359. break;
  360. case 'integer':
  361. $field = new \Symfony\Component\Form\IntegerField($name, $description['options']);
  362. break;
  363. case 'decimal':
  364. $field = new \Symfony\Component\Form\NumberField($name, $description['options']);
  365. break;
  366. case 'datetime':
  367. $field = new \Symfony\Component\Form\DateTimeField($name, $description['options']);
  368. break;
  369. case 'date':
  370. $field = new \Symfony\Component\Form\DateField($name, $description['options']);
  371. break;
  372. case 'choice':
  373. $field = new \Symfony\Component\Form\ChoiceField($name, $description['options']);
  374. break;
  375. case 'array':
  376. $field = new \Symfony\Component\Form\FieldGroup($name, $description['options']);
  377. $values = $description['reflection']->getValue($object);
  378. foreach((array)$values as $k => $v) {
  379. $field->add(new \Symfony\Component\Form\TextField($k));
  380. }
  381. break;
  382. default:
  383. throw new \RuntimeException(sprintf('unknow type `%s`', $description['type']));
  384. }
  385. $form->add($field);
  386. }
  387. return $form;
  388. }
  389. public function setBaseControllerName($base_controller_name)
  390. {
  391. $this->base_controller_name = $base_controller_name;
  392. }
  393. public function getBaseControllerName()
  394. {
  395. return $this->base_controller_name;
  396. }
  397. public function setBaseRoute($base_route)
  398. {
  399. $this->base_route = $base_route;
  400. }
  401. public function getBaseRoute()
  402. {
  403. return $this->base_route;
  404. }
  405. public function setConfigurationPool($configuration_pool)
  406. {
  407. $this->configuration_pool = $configuration_pool;
  408. }
  409. public function getConfigurationPool()
  410. {
  411. return $this->configuration_pool;
  412. }
  413. public function setCode($code)
  414. {
  415. $this->code = $code;
  416. }
  417. public function getCode()
  418. {
  419. return $this->code;
  420. }
  421. public function setLabel($label)
  422. {
  423. $this->label = $label;
  424. }
  425. public function getLabel()
  426. {
  427. return $this->label;
  428. }
  429. }