Admin.php 37 KB

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