Admin.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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\Admin;
  11. use Symfony\Component\DependencyInjection\ContainerAware;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. use Symfony\Component\Form\Form;
  14. use Sonata\BaseApplicationBundle\Form\FormMapper;
  15. use Sonata\BaseApplicationBundle\Datagrid\ListMapper;
  16. use Sonata\BaseApplicationBundle\Datagrid\DatagridMapper;
  17. use Sonata\BaseApplicationBundle\Datagrid\Datagrid;
  18. use Knplabs\MenuBundle\Menu;
  19. use Knplabs\MenuBundle\MenuItem;
  20. abstract class Admin extends ContainerAware
  21. {
  22. protected $class;
  23. protected $list = array();
  24. protected $listFieldDescriptions = array();
  25. protected $form = array();
  26. protected $formFieldDescriptions = array();
  27. protected $filter = array();
  28. protected $filterFieldDescriptions = array();
  29. protected $maxPerPage = 25;
  30. protected $baseRouteName;
  31. protected $baseRoutePattern;
  32. protected $baseControllerName;
  33. protected $formGroups = false;
  34. /**
  35. *
  36. * @var string the classname label (used in the title/breadcrumb ...)
  37. */
  38. protected $classnameLabel;
  39. /**
  40. *
  41. * @var string the translation domain to be used to translate messages
  42. */
  43. protected $translationDomain = 'BaseApplicationBundle';
  44. /**
  45. *
  46. * @var array options to set to the form (ie, validation_groups)
  47. */
  48. protected $formOptions = array();
  49. // note : don't like this, but havn't find a better way to do it
  50. protected $configurationPool;
  51. protected $code;
  52. protected $label;
  53. protected $urls = array();
  54. protected $subject;
  55. /**
  56. * define a Collection of child admin, ie /admin/order/{id}/order-element/{childId}
  57. *
  58. * @var array
  59. */
  60. protected $children = array();
  61. /**
  62. * reference the parent collection
  63. *
  64. * @var Admin
  65. */
  66. protected $parent = null;
  67. /**
  68. * The base code route refer to the prefix used to generate the route name
  69. *
  70. * @var string
  71. */
  72. protected $baseCodeRoute = '';
  73. /**
  74. * The related field reflection, ie if OrderElement is linked to Order,
  75. * then the $parentReflectionProperty must be the ReflectionProperty of
  76. * the order (OrderElement::$order)
  77. *
  78. * @var \ReflectionProperty $parentReflectionProperty
  79. */
  80. protected $parentAssociationMapping = null;
  81. /**
  82. * Reference the parent FieldDescription related to this admin
  83. * only set for FieldDescription which is associated to an Sub Admin instance
  84. *
  85. * @var FieldDescription
  86. */
  87. protected $parentFieldDescription;
  88. /**
  89. * If true then the current admin is part of the nested admin set (from the url)
  90. *
  91. * @var boolean
  92. */
  93. protected $currentChild = false;
  94. /**
  95. * The uniqid is used to avoid clashing with 2 admin related to the code
  96. * ie: a Block linked to a Block
  97. *
  98. * @var
  99. */
  100. protected $uniqid;
  101. protected $loaded = array(
  102. 'form_fields' => false,
  103. 'form_groups' => false,
  104. 'list_fields' => false,
  105. 'filter_fields' => false,
  106. 'urls' => false,
  107. );
  108. protected $choicesCache = array();
  109. /**
  110. * return the entity manager
  111. *
  112. * @return EntityManager
  113. */
  114. abstract public function getEntityManager();
  115. abstract public function getListBuilder();
  116. abstract public function getFormBuilder();
  117. abstract public function getDatagridBuilder();
  118. abstract public function getClassMetaData();
  119. /**
  120. * This method can be overwritten to tweak the form construction, by default the form
  121. * is built by reading the FieldDescription
  122. *
  123. * @return void
  124. */
  125. protected function configureFormFields(FormMapper $form)
  126. {
  127. }
  128. protected function configureListFields(ListMapper $list)
  129. {
  130. }
  131. protected function configureDatagridFilters(DatagridMapper $filter)
  132. {
  133. }
  134. public function __construct($code, ContainerInterface $container)
  135. {
  136. $this->code = $code;
  137. $this->setContainer($container);
  138. $this->configure();
  139. }
  140. public function configure()
  141. {
  142. $this->uniqid = uniqid();
  143. if($this->parentAssociationMapping) {
  144. if(!isset($this->getClassMetaData()->associationMappings[$this->parentAssociationMapping])) {
  145. throw new \RuntimeException(sprintf('The value set to `relatedReflectionProperty` refer to a non existant association', $this->relatedReflectionProperty));
  146. }
  147. $this->parentAssociationMapping = $this->getClassMetaData()->associationMappings[$this->parentAssociationMapping];
  148. }
  149. if(!$this->classnameLabel) {
  150. $this->classnameLabel = $this->urlize(substr($this->class, strrpos($this->class, '\\') + 1), '_');
  151. }
  152. }
  153. public function configureUrls()
  154. {
  155. }
  156. public function preUpdate($object)
  157. {
  158. }
  159. public function postUpdate($object)
  160. {
  161. }
  162. public function preInsert($object)
  163. {
  164. }
  165. public function postInsert($object)
  166. {
  167. }
  168. /**
  169. * build the list FieldDescription array
  170. *
  171. * @return void
  172. */
  173. protected function buildListFieldDescriptions()
  174. {
  175. if ($this->loaded['list_fields']) {
  176. return;
  177. }
  178. $this->loaded['list_fields'] = true;
  179. $this->listFieldDescriptions = self::getBaseFields($this->getClassMetaData(), $this->list);
  180. // normalize field
  181. foreach ($this->listFieldDescriptions as $fieldDescription) {
  182. $this->getListBuilder()->fixFieldDescription($this, $fieldDescription);
  183. }
  184. if (!isset($this->listFieldDescriptions['_batch'])) {
  185. $fieldDescription = new FieldDescription();
  186. $fieldDescription->setOptions(array(
  187. 'label' => 'batch',
  188. 'code' => '_batch',
  189. 'type' => 'batch',
  190. ));
  191. $fieldDescription->setTemplate('SonataBaseApplicationBundle:CRUD:list__batch.twig.html');
  192. $this->listFieldDescriptions = array( '_batch' => $fieldDescription ) + $this->listFieldDescriptions;
  193. }
  194. return $this->listFieldDescriptions;
  195. }
  196. /**
  197. * build the filter FieldDescription array
  198. *
  199. * @return void
  200. */
  201. public function buildFilterFieldDescriptions()
  202. {
  203. if ($this->loaded['filter_fields']) {
  204. return;
  205. }
  206. $this->loaded['filter_fields'] = true;
  207. $this->filterFieldDescriptions = self::getBaseFields($this->getClassMetaData(), $this->filter);
  208. // ok, try to limit to add parent filter
  209. $parentAssociationMapping = $this->getParentAssociationMapping();
  210. if ($parentAssociationMapping) {
  211. $fieldName = $parentAssociationMapping['fieldName'];
  212. $this->filterFieldDescriptions[$fieldName] = new FieldDescription;
  213. $this->filterFieldDescriptions[$fieldName]->setName($parentAssociationMapping['fieldName']);
  214. $this->filterFieldDescriptions[$fieldName]->setAssociationMapping($parentAssociationMapping);
  215. }
  216. foreach ($this->filterFieldDescriptions as $fieldDescription) {
  217. $this->getDatagridBuilder()->fixFieldDescription($this, $fieldDescription);
  218. }
  219. }
  220. /**
  221. * return the name of the parent related field, so the field can be use to set the default
  222. * value (ie the parent object) or to filter the object
  223. *
  224. * @return string the name of the parent related field
  225. */
  226. public function getParentAssociationMapping()
  227. {
  228. return $this->parentAssociationMapping;
  229. }
  230. /**
  231. * Build the form FieldDescription collection
  232. *
  233. * @return void
  234. */
  235. protected function buildFormFieldDescriptions()
  236. {
  237. if ($this->loaded['form_fields']) {
  238. return;
  239. }
  240. $this->loaded['form_fields'] = true;
  241. $this->formFieldDescriptions = self::getBaseFields($this->getClassMetaData(), $this->form);
  242. foreach ($this->formFieldDescriptions as $name => &$fieldDescription) {
  243. $this->getFormBuilder()->fixFieldDescription($this, $fieldDescription);
  244. // unset the identifier field as it is not required to update an object
  245. if ($fieldDescription->isIdentifier()) {
  246. unset($this->formFieldDescriptions[$name]);
  247. }
  248. }
  249. }
  250. /**
  251. * make sure the base fields are set in the correct format
  252. *
  253. * @param $selected_fields
  254. * @return array
  255. */
  256. static public function getBaseFields($metadata, $selectedFields)
  257. {
  258. $fields = array();
  259. // make sure we works with array
  260. foreach ($selectedFields as $name => $options) {
  261. $description = new FieldDescription;
  262. if (!is_array($options)) {
  263. $name = $options;
  264. $options = array();
  265. }
  266. $description->setName($name);
  267. $description->setOptions($options);
  268. $fields[$name] = $description;
  269. }
  270. return $fields;
  271. }
  272. /**
  273. * return the baseRoutePattern used to generate the routing information
  274. *
  275. * @throws RuntimeException
  276. * @return string the baseRoutePattern used to generate the routing information
  277. */
  278. public function getBaseRoutePattern()
  279. {
  280. if (!$this->baseRoutePattern) {
  281. preg_match('@(Application|Bundle)\\\([A-Za-z]*)\\\([A-Za-z]*)Bundle\\\(Entity|Document)\\\([A-Za-z]*)@', $this->getClass(), $matches);
  282. if(!$matches) {
  283. throw new \RuntimeException(sprintf('Please define a default `baseRoutePattern` value for the admin class `%s`', get_class($this)));
  284. }
  285. if ($this->isChild()) { // the admin class is a child, prefix it with the parent route name
  286. $this->baseRoutePattern = sprintf('%s/{id}/%s',
  287. $this->getParent()->getBaseRoutePattern(),
  288. $this->urlize($matches[5], '-')
  289. );
  290. } else {
  291. $this->baseRoutePattern = sprintf('/%s/%s/%s',
  292. $this->urlize($matches[2], '-'),
  293. $this->urlize($matches[3], '-'),
  294. $this->urlize($matches[5], '-')
  295. );
  296. }
  297. }
  298. return $this->baseRoutePattern;
  299. }
  300. /**
  301. * return the baseRouteName used to generate the routing information
  302. *
  303. * @throws RuntimeException
  304. * @return string the baseRouteName used to generate the routing information
  305. */
  306. public function getBaseRouteName()
  307. {
  308. if (!$this->baseRouteName) {
  309. preg_match('@(Application|Bundle)\\\([A-Za-z]*)\\\([A-Za-z]*)Bundle\\\(Entity|Document)\\\([A-Za-z]*)@', $this->getClass(), $matches);
  310. if(!$matches) {
  311. throw new \RuntimeException(sprintf('Please define a default `baseRouteName` value for the admin class `%s`', get_class($this)));
  312. }
  313. if ($this->isChild()) { // the admin class is a child, prefix it with the parent route name
  314. $this->baseRouteName = sprintf('%s_%s',
  315. $this->getParent()->getBaseRouteName(),
  316. $this->urlize($matches[5])
  317. );
  318. } else {
  319. $this->baseRouteName = sprintf('admin_%s_%s_%s',
  320. $this->urlize($matches[2]),
  321. $this->urlize($matches[3]),
  322. $this->urlize($matches[5])
  323. );
  324. }
  325. }
  326. return $this->baseRouteName;
  327. }
  328. /**
  329. * urlize the given word
  330. *
  331. * @param string $word
  332. * @param string $sep the separator
  333. */
  334. public function urlize($word, $sep = '_')
  335. {
  336. return strtolower(preg_replace('~(?<=\\w)([A-Z])~', $sep.'$1', $word));
  337. }
  338. /**
  339. * return the class name handled by the Admin instance
  340. *
  341. * @return string the class name handled by the Admin instance
  342. */
  343. public function getClass()
  344. {
  345. return $this->class;
  346. }
  347. /**
  348. * return the list of batchs actions
  349. *
  350. * @return array the list of batchs actions
  351. */
  352. public function getBatchActions()
  353. {
  354. return array(
  355. 'delete' => 'action_delete'
  356. );
  357. }
  358. /**
  359. * return the list of available urls
  360. *
  361. * @return array the list of available urls
  362. */
  363. public function getUrls($baseCode = '')
  364. {
  365. $this->buildUrls($baseCode);
  366. return $this->urls;
  367. }
  368. /**
  369. * return the parameter representing router id, ie: {id} or {childId}
  370. *
  371. * @return string
  372. */
  373. public function getRouterIdParameter()
  374. {
  375. return $this->isChild() ? '{childId}' : '{id}';
  376. }
  377. /**
  378. * return the parameter representing request id, ie: id or childId
  379. *
  380. * @return string
  381. */
  382. public function getIdParameter()
  383. {
  384. return $this->isChild() ? 'childId' : 'id';
  385. }
  386. /**
  387. * Build all the related urls to the current admin
  388. *
  389. * @param string $baseCode
  390. * @return void
  391. */
  392. public function buildUrls($baseCode = '')
  393. {
  394. if ($this->loaded['urls']) {
  395. return;
  396. }
  397. $this->baseCodeRoute = $baseCode;
  398. $this->loaded['urls'] = true;
  399. $this->urls = array(
  400. $baseCode . 'list' => array(
  401. 'name' => $this->getBaseRouteName().'_list',
  402. 'pattern' => $this->getBaseRoutePattern().'/list',
  403. 'defaults' => array(
  404. '_controller' => $this->getBaseControllerName().':list'
  405. ),
  406. 'requirements' => array(),
  407. 'options' => array(),
  408. 'params' => array(),
  409. ),
  410. $baseCode . 'create' => array(
  411. 'name' => $this->getBaseRouteName().'_create',
  412. 'pattern' => $this->getBaseRoutePattern().'/create',
  413. 'defaults' => array(
  414. '_controller' => $this->getBaseControllerName().':create'
  415. ),
  416. 'requirements' => array(),
  417. 'options' => array(),
  418. 'params' => array(),
  419. ),
  420. $baseCode . 'edit' => array(
  421. 'name' => $this->getBaseRouteName().'_edit',
  422. 'pattern' => $this->getBaseRoutePattern().'/'.$this->getRouterIdParameter().'/edit',
  423. 'defaults' => array(
  424. '_controller' => $this->getBaseControllerName().':edit'
  425. ),
  426. 'requirements' => array(),
  427. 'options' => array(),
  428. 'params' => array(),
  429. ),
  430. $baseCode . 'update' => array(
  431. 'name' => $this->getBaseRouteName().'_update',
  432. 'pattern' => $this->getBaseRoutePattern().'/update',
  433. 'defaults' => array(
  434. '_controller' => $this->getBaseControllerName().':update'
  435. ),
  436. 'requirements' => array(),
  437. 'options' => array(),
  438. 'params' => array(),
  439. ),
  440. $baseCode . 'batch' => array(
  441. 'name' => $this->getBaseRouteName().'_batch',
  442. 'pattern' => $this->getBaseRoutePattern().'/batch',
  443. 'defaults' => array(
  444. '_controller' => $this->getBaseControllerName().':batch'
  445. ),
  446. 'requirements' => array(),
  447. 'options' => array(),
  448. 'params' => array(),
  449. )
  450. );
  451. // add children urls
  452. foreach ($this->getChildren() as $code => $children) {
  453. $this->urls = array_merge($this->urls, $children->getUrls($code.'.'));
  454. }
  455. $this->configureUrls();
  456. }
  457. /**
  458. * return the url defined by the $name
  459. *
  460. * @param $name
  461. * @return bool
  462. */
  463. public function getUrl($name)
  464. {
  465. $urls = $this->getUrls();
  466. if (!isset($urls[$name])) {
  467. return false;
  468. }
  469. return $urls[$name];
  470. }
  471. /**
  472. * generate the url with the given $name
  473. *
  474. * @throws RuntimeException
  475. * @param $name
  476. * @param array $params
  477. *
  478. * @return return a complete url
  479. */
  480. public function generateUrl($name, array $params = array())
  481. {
  482. // if the admin is a child we automatically append the parent's id
  483. if($this->isChild()) {
  484. $name = $this->baseCodeRoute.$name;
  485. // twig template does not accept variable hash key ... so cannot use admin.idparameter ...
  486. // switch value
  487. if(isset($params['id'])) {
  488. $params[$this->getIdParameter()] = $params['id'];
  489. unset($params['id']);
  490. }
  491. $params[$this->getParent()->getIdParameter()] = $this->container->get('request')->get($this->getParent()->getIdParameter());
  492. }
  493. // if the admin is linked to a FieldDescription (ie, embeded widget)
  494. if($this->hasParentFieldDescription()) {
  495. $params['uniqid'] = $this->getUniqid();
  496. $params['code'] = $this->getCode();
  497. $params['pcode'] = $this->getParentFieldDescription()->getAdmin()->getCode();
  498. $params['puniqid'] = $this->getParentFieldDescription()->getAdmin()->getUniqid();
  499. }
  500. if($name == 'update' || substr($name, -7) == '.update') {
  501. $params['uniqid'] = $this->getUniqid();
  502. $params['code'] = $this->getCode();
  503. }
  504. $url = $this->getUrl($name);
  505. if (!$url) {
  506. throw new \RuntimeException(sprintf('unable to find the url `%s`', $name));
  507. }
  508. return $this->container->get('router')->generate($url['name'], $params);
  509. }
  510. /**
  511. * return the list template
  512. *
  513. * @return string the list template
  514. */
  515. public function getListTemplate()
  516. {
  517. return 'SonataBaseApplicationBundle:CRUD:list.twig.html';
  518. }
  519. /**
  520. * return the edit template
  521. *
  522. * @return string the edit template
  523. */
  524. public function getEditTemplate()
  525. {
  526. return 'SonataBaseApplicationBundle:CRUD:edit.twig.html';
  527. }
  528. /**
  529. * return the reflection fields related to the classname
  530. *
  531. * @return array the reflection fields related to the classname
  532. */
  533. public function getReflectionFields()
  534. {
  535. return $this->getClassMetaData()->reflFields;
  536. }
  537. /**
  538. * return a instance of the related classname
  539. *
  540. * @return object a instance of the related classname
  541. */
  542. public function getNewInstance()
  543. {
  544. $class = $this->getClass();
  545. return new $class;
  546. }
  547. /**
  548. *
  549. * @return Form the base form
  550. */
  551. public function getBaseForm($object, $options = array())
  552. {
  553. return $this->getFormBuilder()->getBaseForm(
  554. 'object_'.$this->getUniqid(),
  555. $object,
  556. array_merge($this->formOptions, $options)
  557. );
  558. }
  559. /**
  560. *
  561. * @return Form the base form
  562. */
  563. public function getBaseDatagrid($values = array())
  564. {
  565. return new Datagrid(
  566. $this->getClass(),
  567. $this->getEntityManager(),
  568. $values
  569. );
  570. }
  571. /**
  572. * attach an admin instance to the given FieldDescription
  573. *
  574. */
  575. public function attachAdminClass(FieldDescription $fieldDescription)
  576. {
  577. $pool = $this->getConfigurationPool();
  578. $admin = $pool->getAdminByClass($fieldDescription->getTargetEntity());
  579. if (!$admin) {
  580. throw new \RuntimeException(sprintf('You must define an Admin class for the `%s` field (targetEntity=%s)', $fieldDescription->getFieldName(), $fieldDescription->getTargetEntity()));
  581. }
  582. $fieldDescription->setAssociationAdmin($admin);
  583. }
  584. /**
  585. * return the target objet
  586. *
  587. * @param $id
  588. * @return
  589. */
  590. public function getObject($id)
  591. {
  592. return $this->getEntityManager()
  593. ->find($this->getClass(), $id);
  594. }
  595. /**
  596. * build the form group array
  597. *
  598. * @return void
  599. */
  600. public function buildFormGroups()
  601. {
  602. if ($this->loaded['form_groups']) {
  603. return;
  604. }
  605. $this->loaded['form_groups'] = true;
  606. if (!$this->formGroups) {
  607. $this->formGroups = array(
  608. false => array('fields' => array_keys($this->getFormFieldDescriptions()))
  609. );
  610. }
  611. // normalize array
  612. foreach ($this->formGroups as $name => $group) {
  613. if (!isset($this->formGroups[$name]['collapsed'])) {
  614. $this->formGroups[$name]['collapsed'] = false;
  615. }
  616. }
  617. }
  618. /**
  619. * return a form depend on the given $object
  620. *
  621. * @param $object
  622. * @return Symfony\Component\Form\Form
  623. */
  624. public function getForm($object, array $options = array())
  625. {
  626. // append parent object if any
  627. // todo : clean the way the Admin class can retrieve set the object
  628. if ($this->isChild() && $this->getParentAssociationMapping()) {
  629. $mapping = $this->getParentAssociationMapping();
  630. $parent = $this->getParent()->getObject($this->container->get('request')->get($this->getParent()->getIdParameter()));
  631. $propertyPath = new \Symfony\Component\Form\PropertyPath($mapping['fieldName']);
  632. $propertyPath->setValue($object, $parent);
  633. }
  634. $form = $this->getBaseForm($object, $options);
  635. $mapper = new FormMapper($this->getFormBuilder(), $form, $this);
  636. $this->buildFormFieldDescriptions();
  637. $this->configureFormFields($mapper);
  638. foreach ($this->getFormFieldDescriptions() as $fieldDescription) {
  639. $mapper->add($fieldDescription);
  640. }
  641. return $form;
  642. }
  643. /**
  644. * return a list depend on the given $object
  645. *
  646. * @param $object
  647. * @return Symfony\Component\Datagrid\ListCollection
  648. */
  649. public function getList(array $options = array())
  650. {
  651. $list = $this->getListBuilder()->getBaseList($options);
  652. $mapper = new ListMapper($this->getListBuilder(), $list, $this);
  653. $this->buildListFieldDescriptions();
  654. $this->configureListFields($mapper);
  655. foreach ($this->getListFieldDescriptions() as $fieldDescription) {
  656. $mapper->add($fieldDescription);
  657. }
  658. return $list;
  659. }
  660. /**
  661. * return a list depend on the given $object
  662. *
  663. * @param $object
  664. * @return Symfony\Component\Datagrid\Datagrid
  665. */
  666. public function getDatagrid()
  667. {
  668. $parameters = $this->container->get('request')->query->all();
  669. $datagrid = $this->getBaseDatagrid($parameters);
  670. $datagrid->setMaxPerPage($this->maxPerPage);
  671. if($this->isChild() && $this->getParentAssociationMapping()) {
  672. $mapping = $this->getParentAssociationMapping();
  673. $parameters[$mapping['fieldName']] = $this->container->get('request')->get($this->getParent()->getIdParameter());
  674. }
  675. $datagrid->setValues($parameters);
  676. $mapper = new DatagridMapper($this->getDatagridBuilder(), $datagrid, $this);
  677. $this->buildFilterFieldDescriptions();
  678. $this->configureDatagridFilters($mapper);
  679. foreach ($this->getFilterFieldDescriptions() as $fieldDescription) {
  680. $mapper->add($fieldDescription);
  681. }
  682. return $datagrid;
  683. }
  684. /**
  685. * Build the side menu related to the current action
  686. *
  687. * @return MenuItem|false
  688. */
  689. public function getSideMenu($action)
  690. {
  691. return false;
  692. }
  693. /**
  694. * return the root code
  695. *
  696. * @return string the root code
  697. */
  698. public function getRootCode()
  699. {
  700. return $this->getRoot()->getCode();
  701. }
  702. /**
  703. * return the master admin
  704. *
  705. * @return Admin the root admin class
  706. */
  707. public function getRoot()
  708. {
  709. $parentFieldDescription = $this->getParentFieldDescription();
  710. if (!$parentFieldDescription) {
  711. return $this;
  712. }
  713. return $parentFieldDescription->getAdmin()->getRoot();
  714. }
  715. public function setBaseControllerName($baseControllerName)
  716. {
  717. $this->baseControllerName = $baseControllerName;
  718. }
  719. public function getBaseControllerName()
  720. {
  721. return $this->baseControllerName;
  722. }
  723. public function getConfigurationPool()
  724. {
  725. return $this->container->get('base_application.admin.pool');
  726. }
  727. public function getCode()
  728. {
  729. return $this->code;
  730. }
  731. public function setLabel($label)
  732. {
  733. $this->label = $label;
  734. }
  735. public function getLabel()
  736. {
  737. return $this->label;
  738. }
  739. public function setMaxPerPage($maxPerPage)
  740. {
  741. $this->maxPerPage = $maxPerPage;
  742. }
  743. public function getMaxPerPage()
  744. {
  745. return $this->maxPerPage;
  746. }
  747. public function setFormGroups($formGroups)
  748. {
  749. $this->formGroups = $formGroups;
  750. }
  751. public function getFormGroups()
  752. {
  753. $this->buildFormGroups();
  754. return $this->formGroups;
  755. }
  756. /**
  757. * set the parent FieldDescription
  758. *
  759. * @param FieldDescription $parentFieldDescription
  760. * @return void
  761. */
  762. public function setParentFieldDescription(FieldDescription $parentFieldDescription)
  763. {
  764. $this->parentFieldDescription = $parentFieldDescription;
  765. }
  766. /**
  767. *
  768. * @return FieldDescription the parent field description
  769. */
  770. public function getParentFieldDescription()
  771. {
  772. return $this->parentFieldDescription;
  773. }
  774. /**
  775. * return true if the Admin is linked to a parent FieldDescription
  776. *
  777. * @return bool
  778. */
  779. public function hasParentFieldDescription()
  780. {
  781. return $this->parentFieldDescription instanceof FieldDescription;
  782. }
  783. /**
  784. * set the subject linked to the admin, the subject is the related model
  785. *
  786. * @param object $subject
  787. * @return void
  788. */
  789. public function setSubject($subject)
  790. {
  791. $this->subject = $subject;
  792. }
  793. /**
  794. * return the subject, if none is set try to load one from the request
  795. *
  796. * @return $object the subject
  797. */
  798. public function getSubject()
  799. {
  800. if($this->subject === null) {
  801. $id = $this->container->get('request')->get($this->getIdParameter());
  802. if(!is_numeric($id)) {
  803. $this->subject = false;
  804. } else {
  805. $this->subject = $this->getEntityManager()->find(
  806. $this->getClass(),
  807. $id
  808. );
  809. }
  810. }
  811. return $this->subject;
  812. }
  813. /**
  814. * build and return the collection of form FieldDescription
  815. *
  816. * @return array collection of form FieldDescription
  817. */
  818. public function getFormFieldDescriptions()
  819. {
  820. $this->buildFormFieldDescriptions();
  821. return $this->formFieldDescriptions;
  822. }
  823. /**
  824. * return the form FieldDescription with the given $name
  825. *
  826. * @param string $name
  827. * @return FieldDescription
  828. */
  829. public function getFormFieldDescription($name) {
  830. return $this->hasFormFieldDescription($name) ? $this->formFieldDescriptions[$name] : null;
  831. }
  832. /**
  833. * return true if the admin has a FieldDescription with the given $name
  834. *
  835. * @param string $name
  836. * @return bool
  837. */
  838. public function hasFormFieldDescription($name)
  839. {
  840. $this->buildFormFieldDescriptions();
  841. return array_key_exists($name, $this->formFieldDescriptions) ? true : false;
  842. }
  843. /**
  844. * add a FieldDescription
  845. *
  846. * @param string $name
  847. * @param FieldDescription $fieldDescription
  848. * @return void
  849. */
  850. public function addFormFieldDescription($name, FieldDescription $fieldDescription)
  851. {
  852. $this->formFieldDescriptions[$name] = $fieldDescription;
  853. }
  854. /**
  855. * remove a FieldDescription
  856. *
  857. * @param string $name
  858. * @return void
  859. */
  860. public function removeFormFieldDescription($name)
  861. {
  862. unset($this->formFieldDescriptions[$name]);
  863. }
  864. /**
  865. * return the collection of list FieldDescriptions
  866. *
  867. * @return array
  868. */
  869. public function getListFieldDescriptions()
  870. {
  871. $this->buildListFieldDescriptions();
  872. return $this->listFieldDescriptions;
  873. }
  874. /**
  875. * return a list FieldDescription
  876. *
  877. * @param string $name
  878. * @return FieldDescription
  879. */
  880. public function getListFieldDescription($name) {
  881. return $this->hasListFieldDescription($name) ? $this->listFieldDescriptions[$name] : null;
  882. }
  883. /**
  884. * return true if the list FieldDescription exists
  885. *
  886. * @param string $name
  887. * @return bool
  888. */
  889. public function hasListFieldDescription($name)
  890. {
  891. $this->buildListFieldDescriptions();
  892. return array_key_exists($name, $this->listFieldDescriptions) ? true : false;
  893. }
  894. /**
  895. * add a list FieldDescription
  896. *
  897. * @param string $name
  898. * @param FieldDescription $fieldDescription
  899. * @return void
  900. */
  901. public function addListFieldDescription($name, FieldDescription $fieldDescription)
  902. {
  903. $this->listFieldDescriptions[$name] = $fieldDescription;
  904. }
  905. /**
  906. * remove a list FieldDescription
  907. *
  908. * @param string $name
  909. * @return void
  910. */
  911. public function removeListFieldDescription($name)
  912. {
  913. unset($this->listFieldDescriptions[$name]);
  914. }
  915. /**
  916. * return a filter FieldDescription
  917. *
  918. * @param string $name
  919. * @return array|null
  920. */
  921. public function getFilterFieldDescription($name) {
  922. return $this->hasFilterFieldDescription($name) ? $this->filterFieldDescriptions[$name] : null;
  923. }
  924. /**
  925. * return true if the filter FieldDescription exists
  926. *
  927. * @param string $name
  928. * @return bool
  929. */
  930. public function hasFilterFieldDescription($name)
  931. {
  932. $this->buildFilterFieldDescriptions();
  933. return array_key_exists($name, $this->filterFieldDescriptions) ? true : false;
  934. }
  935. /**
  936. * add a filter FieldDescription
  937. *
  938. * @param string $name
  939. * @param FieldDescription $fieldDescription
  940. * @return void
  941. */
  942. public function addFilterFieldDescription($name, FieldDescription $fieldDescription)
  943. {
  944. $this->filterFieldDescriptions[$name] = $fieldDescription;
  945. }
  946. /**
  947. * remove a filter FieldDescription
  948. *
  949. * @param string $name
  950. */
  951. public function removeFilterFieldDescription($name)
  952. {
  953. unset($this->filterFieldDescriptions[$name]);
  954. }
  955. /**
  956. * return the filter FieldDescription collection
  957. *
  958. * @param array filter FieldDescription collection
  959. */
  960. public function getFilterFieldDescriptions()
  961. {
  962. $this->buildFilterFieldDescriptions();
  963. return $this->filterFieldDescriptions;
  964. }
  965. /**
  966. * add an Admin child to the current one
  967. *
  968. * @param string $code
  969. * @param Admin $child
  970. * @return void
  971. */
  972. public function addChild($code, Admin $child)
  973. {
  974. $this->children[$code] = $child;
  975. $child->setParent($this);
  976. }
  977. /**
  978. * return true or false if an Admin child exists for the given $code
  979. *
  980. * @param string $code
  981. * @return Admin|bool
  982. */
  983. public function hasChild($code)
  984. {
  985. return isset($this->children[$code]) ? $this->children[$code] : false;
  986. }
  987. /**
  988. * return an collection of admin children
  989. *
  990. * @return array list of Admin children
  991. */
  992. public function getChildren()
  993. {
  994. return $this->children;
  995. }
  996. /**
  997. * return an admin child with the given $code
  998. *
  999. * @param string $code
  1000. * @return array|null
  1001. */
  1002. public function getChild($code)
  1003. {
  1004. return $this->hasChild($code) ? $this->children[$code] : null;
  1005. }
  1006. /**
  1007. * set the Parent Admin
  1008. *
  1009. * @param Admin $parent
  1010. * @return void
  1011. */
  1012. public function setParent(Admin $parent)
  1013. {
  1014. $this->parent = $parent;
  1015. }
  1016. /**
  1017. * get the Parent Admin
  1018. *
  1019. * @return Admin|null
  1020. */
  1021. public function getParent()
  1022. {
  1023. return $this->parent;
  1024. }
  1025. /**
  1026. * return true if the Admin class has an Parent Admin defined
  1027. *
  1028. * @return boolean
  1029. */
  1030. public function isChild()
  1031. {
  1032. return $this->parent instanceof Admin;
  1033. }
  1034. /**
  1035. * return true if the admin has childre, false otherwise
  1036. *
  1037. * @return bool if the admin has children
  1038. */
  1039. public function hasChildren()
  1040. {
  1041. return count($this->children) > 0;
  1042. }
  1043. /**
  1044. * set the uniqid
  1045. *
  1046. * @param $uniqid
  1047. * @return void
  1048. */
  1049. public function setUniqid($uniqid)
  1050. {
  1051. $this->uniqid = $uniqid;
  1052. }
  1053. /**
  1054. * return the uniqid
  1055. *
  1056. * @return integer
  1057. */
  1058. public function getUniqid()
  1059. {
  1060. return $this->uniqid;
  1061. }
  1062. /**
  1063. * return the classname label
  1064. *
  1065. * @return string the classname label
  1066. */
  1067. public function getClassnameLabel()
  1068. {
  1069. return $this->classnameLabel;
  1070. }
  1071. /**
  1072. * generate the breadcrumbs array
  1073. *
  1074. * @param $action
  1075. * @param \Knplabs\MenuBundle\MenuItem|null $menu
  1076. * @return array the breadcrumbs
  1077. */
  1078. public function getBreadcrumbs($action, MenuItem $menu = null)
  1079. {
  1080. $menu = $menu ?: new Menu;
  1081. $child = $menu->addChild(
  1082. $this->trans(sprintf('link_%s_list', $this->getClassnameLabel())),
  1083. $this->generateUrl('list')
  1084. );
  1085. $childAdmin = $this->getCurrentChildAdmin();
  1086. if ($childAdmin) {
  1087. $id = $this->container->get('request')->get($this->getIdParameter());
  1088. $child = $child->addChild(
  1089. (string) $this->getSubject(),
  1090. $this->generateUrl('edit', array('id' => $id))
  1091. );
  1092. return $childAdmin->getBreadcrumbs($action, $child);
  1093. } elseif ($this->isChild()) {
  1094. if($action != 'list') {
  1095. $menu = $menu->addChild(
  1096. $this->trans(sprintf('link_%s_list', $this->getClassnameLabel())),
  1097. $this->generateUrl('list')
  1098. );
  1099. }
  1100. $breadcrumbs = $menu->getBreadcrumbsArray(
  1101. $this->trans(sprintf('link_%s_%s', $this->getClassnameLabel(), $action))
  1102. );
  1103. } else if($action != 'list') {
  1104. $breadcrumbs = $child->getBreadcrumbsArray(
  1105. $this->trans(sprintf('link_%s_%s', $this->getClassnameLabel(), $action))
  1106. );
  1107. } else {
  1108. $breadcrumbs = $child->getBreadcrumbsArray();
  1109. }
  1110. // the generated $breadcrumbs contains an empty element
  1111. array_shift($breadcrumbs);
  1112. return $breadcrumbs;
  1113. }
  1114. /**
  1115. * set the current child status
  1116. *
  1117. * @param boolean $currentChild
  1118. * @return void
  1119. */
  1120. public function setCurrentChild($currentChild)
  1121. {
  1122. $this->currentChild = $currentChild;
  1123. }
  1124. /**
  1125. * return the current child status
  1126. *
  1127. * @return bool
  1128. */
  1129. public function getCurrentChild()
  1130. {
  1131. return $this->currentChild;
  1132. }
  1133. /**
  1134. * return the current child admin instance
  1135. *
  1136. * @return Admin|null the current child admin instance
  1137. */
  1138. public function getCurrentChildAdmin()
  1139. {
  1140. foreach($this->children as $children) {
  1141. if($children->getCurrentChild()) {
  1142. return $children;
  1143. }
  1144. }
  1145. return null;
  1146. }
  1147. /**
  1148. * translate a message id
  1149. *
  1150. * @param string $id
  1151. * @param array $parameters
  1152. * @param null $domain
  1153. * @param null $locale
  1154. * @return string the translated string
  1155. */
  1156. public function trans($id, array $parameters = array(), $domain = null, $locale = null)
  1157. {
  1158. $domain = $domain ?: $this->translationDomain;
  1159. return $this->container->get('translator')->trans($id, $parameters, $domain, $locale);
  1160. }
  1161. /**
  1162. * set the translation domain
  1163. *
  1164. * @param string $translationDomain the translation domain
  1165. * @return void
  1166. */
  1167. public function setTranslationDomain($translationDomain)
  1168. {
  1169. $this->translationDomain = $translationDomain;
  1170. }
  1171. /**
  1172. * return the translation domain
  1173. *
  1174. * @return string the translation domain
  1175. */
  1176. public function getTranslationDomain()
  1177. {
  1178. return $this->translationDomain;
  1179. }
  1180. }