AbstractAdmin.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project 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\AdminBundle\Admin;
  11. use Doctrine\Common\Util\ClassUtils;
  12. use Knp\Menu\FactoryInterface as MenuFactoryInterface;
  13. use Knp\Menu\ItemInterface;
  14. use Knp\Menu\ItemInterface as MenuItemInterface;
  15. use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
  16. use Sonata\AdminBundle\Builder\FormContractorInterface;
  17. use Sonata\AdminBundle\Builder\ListBuilderInterface;
  18. use Sonata\AdminBundle\Builder\RouteBuilderInterface;
  19. use Sonata\AdminBundle\Builder\ShowBuilderInterface;
  20. use Sonata\AdminBundle\Datagrid\DatagridInterface;
  21. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  22. use Sonata\AdminBundle\Datagrid\ListMapper;
  23. use Sonata\AdminBundle\Datagrid\Pager;
  24. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  25. use Sonata\AdminBundle\Form\FormMapper;
  26. use Sonata\AdminBundle\Model\ModelManagerInterface;
  27. use Sonata\AdminBundle\Route\RouteCollection;
  28. use Sonata\AdminBundle\Route\RouteGeneratorInterface;
  29. use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
  30. use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
  31. use Sonata\AdminBundle\Show\ShowMapper;
  32. use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
  33. use Sonata\CoreBundle\Model\Metadata;
  34. use Sonata\CoreBundle\Validator\Constraints\InlineConstraint;
  35. use Sonata\CoreBundle\Validator\ErrorElement;
  36. use Symfony\Component\Form\Form;
  37. use Symfony\Component\Form\FormBuilderInterface;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\PropertyAccess\PropertyPath;
  40. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  41. use Symfony\Component\Security\Acl\Model\DomainObjectInterface;
  42. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  43. use Symfony\Component\Translation\TranslatorInterface;
  44. use Symfony\Component\Validator\Validator\ValidatorInterface;
  45. use Symfony\Component\Validator\ValidatorInterface as LegacyValidatorInterface;
  46. /**
  47. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  48. */
  49. abstract class AbstractAdmin implements AdminInterface, DomainObjectInterface
  50. {
  51. const CONTEXT_MENU = 'menu';
  52. const CONTEXT_DASHBOARD = 'dashboard';
  53. const CLASS_REGEX =
  54. '@
  55. (?:([A-Za-z0-9]*)\\\)? # vendor name / app name
  56. (Bundle\\\)? # optional bundle directory
  57. ([A-Za-z0-9]+?)(?:Bundle)?\\\ # bundle name, with optional suffix
  58. (
  59. Entity|Document|Model|PHPCR|CouchDocument|Phpcr|
  60. Doctrine\\\Orm|Doctrine\\\Phpcr|Doctrine\\\MongoDB|Doctrine\\\CouchDB
  61. )\\\(.*)@x';
  62. const MOSAIC_ICON_CLASS = 'fa fa-th-large fa-fw';
  63. /**
  64. * The list FieldDescription constructed from the configureListField method.
  65. *
  66. * @var array
  67. */
  68. protected $listFieldDescriptions = array();
  69. /**
  70. * The show FieldDescription constructed from the configureShowFields method.
  71. *
  72. * @var array
  73. */
  74. protected $showFieldDescriptions = array();
  75. /**
  76. * The list FieldDescription constructed from the configureFormField method.
  77. *
  78. * @var array
  79. */
  80. protected $formFieldDescriptions = array();
  81. /**
  82. * The filter FieldDescription constructed from the configureFilterField method.
  83. *
  84. * @var array
  85. */
  86. protected $filterFieldDescriptions = array();
  87. /**
  88. * The number of result to display in the list.
  89. *
  90. * @var int
  91. */
  92. protected $maxPerPage = 32;
  93. /**
  94. * The maximum number of page numbers to display in the list.
  95. *
  96. * @var int
  97. */
  98. protected $maxPageLinks = 25;
  99. /**
  100. * The base route name used to generate the routing information.
  101. *
  102. * @var string
  103. */
  104. protected $baseRouteName;
  105. /**
  106. * The base route pattern used to generate the routing information.
  107. *
  108. * @var string
  109. */
  110. protected $baseRoutePattern;
  111. /**
  112. * The base name controller used to generate the routing information.
  113. *
  114. * @var string
  115. */
  116. protected $baseControllerName;
  117. /**
  118. * The label class name (used in the title/breadcrumb ...).
  119. *
  120. * @var string
  121. */
  122. protected $classnameLabel;
  123. /**
  124. * The translation domain to be used to translate messages.
  125. *
  126. * @var string
  127. */
  128. protected $translationDomain = 'messages';
  129. /**
  130. * Options to set to the form (ie, validation_groups).
  131. *
  132. * @var array
  133. */
  134. protected $formOptions = array();
  135. /**
  136. * Default values to the datagrid.
  137. *
  138. * @var array
  139. */
  140. protected $datagridValues = array(
  141. '_page' => 1,
  142. '_per_page' => 32,
  143. );
  144. /**
  145. * Predefined per page options.
  146. *
  147. * @var array
  148. */
  149. protected $perPageOptions = array(16, 32, 64, 128, 192);
  150. /**
  151. * Pager type.
  152. *
  153. * @var string
  154. */
  155. protected $pagerType = Pager::TYPE_DEFAULT;
  156. /**
  157. * The code related to the admin.
  158. *
  159. * @var string
  160. */
  161. protected $code;
  162. /**
  163. * The label.
  164. *
  165. * @var string
  166. */
  167. protected $label;
  168. /**
  169. * Whether or not to persist the filters in the session.
  170. *
  171. * @var bool
  172. */
  173. protected $persistFilters = false;
  174. /**
  175. * Array of routes related to this admin.
  176. *
  177. * @var RouteCollection
  178. */
  179. protected $routes;
  180. /**
  181. * The subject only set in edit/update/create mode.
  182. *
  183. * @var object
  184. */
  185. protected $subject;
  186. /**
  187. * Define a Collection of child admin, ie /admin/order/{id}/order-element/{childId}.
  188. *
  189. * @var array
  190. */
  191. protected $children = array();
  192. /**
  193. * Reference the parent collection.
  194. *
  195. * @var AdminInterface|null
  196. */
  197. protected $parent = null;
  198. /**
  199. * The base code route refer to the prefix used to generate the route name.
  200. *
  201. * @var string
  202. */
  203. protected $baseCodeRoute = '';
  204. /**
  205. * The related field reflection, ie if OrderElement is linked to Order,
  206. * then the $parentReflectionProperty must be the ReflectionProperty of
  207. * the order (OrderElement::$order).
  208. *
  209. * @var \ReflectionProperty
  210. */
  211. protected $parentAssociationMapping = null;
  212. /**
  213. * Reference the parent FieldDescription related to this admin
  214. * only set for FieldDescription which is associated to an Sub Admin instance.
  215. *
  216. * @var FieldDescriptionInterface
  217. */
  218. protected $parentFieldDescription;
  219. /**
  220. * If true then the current admin is part of the nested admin set (from the url).
  221. *
  222. * @var bool
  223. */
  224. protected $currentChild = false;
  225. /**
  226. * The uniqid is used to avoid clashing with 2 admin related to the code
  227. * ie: a Block linked to a Block.
  228. *
  229. * @var string
  230. */
  231. protected $uniqid;
  232. /**
  233. * The Entity or Document manager.
  234. *
  235. * @var ModelManagerInterface
  236. */
  237. protected $modelManager;
  238. /**
  239. * The current request object.
  240. *
  241. * @var \Symfony\Component\HttpFoundation\Request
  242. */
  243. protected $request;
  244. /**
  245. * The translator component.
  246. *
  247. * @var \Symfony\Component\Translation\TranslatorInterface
  248. */
  249. protected $translator;
  250. /**
  251. * The related form contractor.
  252. *
  253. * @var FormContractorInterface
  254. */
  255. protected $formContractor;
  256. /**
  257. * The related list builder.
  258. *
  259. * @var ListBuilderInterface
  260. */
  261. protected $listBuilder;
  262. /**
  263. * The related view builder.
  264. *
  265. * @var ShowBuilderInterface
  266. */
  267. protected $showBuilder;
  268. /**
  269. * The related datagrid builder.
  270. *
  271. * @var DatagridBuilderInterface
  272. */
  273. protected $datagridBuilder;
  274. /**
  275. * @var RouteBuilderInterface
  276. */
  277. protected $routeBuilder;
  278. /**
  279. * The datagrid instance.
  280. *
  281. * @var \Sonata\AdminBundle\Datagrid\DatagridInterface
  282. */
  283. protected $datagrid;
  284. /**
  285. * The router instance.
  286. *
  287. * @var RouteGeneratorInterface
  288. */
  289. protected $routeGenerator;
  290. /**
  291. * The generated breadcrumbs.
  292. *
  293. * NEXT_MAJOR : remove this property
  294. *
  295. * @var array
  296. */
  297. protected $breadcrumbs = array();
  298. /**
  299. * @var SecurityHandlerInterface
  300. */
  301. protected $securityHandler = null;
  302. /**
  303. * @var ValidatorInterface|LegacyValidatorInterface
  304. */
  305. protected $validator = null;
  306. /**
  307. * The configuration pool.
  308. *
  309. * @var Pool
  310. */
  311. protected $configurationPool;
  312. /**
  313. * @var MenuItemInterface
  314. */
  315. protected $menu;
  316. /**
  317. * @var MenuFactoryInterface
  318. */
  319. protected $menuFactory;
  320. /**
  321. * @var array
  322. */
  323. protected $loaded = array(
  324. 'view_fields' => false,
  325. 'view_groups' => false,
  326. 'routes' => false,
  327. 'tab_menu' => false,
  328. );
  329. /**
  330. * @var array
  331. */
  332. protected $formTheme = array();
  333. /**
  334. * @var array
  335. */
  336. protected $filterTheme = array();
  337. /**
  338. * @var array
  339. */
  340. protected $templates = array();
  341. /**
  342. * @var AdminExtensionInterface[]
  343. */
  344. protected $extensions = array();
  345. /**
  346. * @var LabelTranslatorStrategyInterface
  347. */
  348. protected $labelTranslatorStrategy;
  349. /**
  350. * Setting to true will enable preview mode for
  351. * the entity and show a preview button in the
  352. * edit/create forms.
  353. *
  354. * @var bool
  355. */
  356. protected $supportsPreviewMode = false;
  357. /**
  358. * Roles and permissions per role.
  359. *
  360. * @var array [role] => array([permission], [permission])
  361. */
  362. protected $securityInformation = array();
  363. protected $cacheIsGranted = array();
  364. /**
  365. * Action list for the search result.
  366. *
  367. * @var string[]
  368. */
  369. protected $searchResultActions = array('edit', 'show');
  370. protected $listModes = array(
  371. 'list' => array(
  372. 'class' => 'fa fa-list fa-fw',
  373. ),
  374. 'mosaic' => array(
  375. 'class' => self::MOSAIC_ICON_CLASS,
  376. ),
  377. );
  378. /**
  379. * The Access mapping.
  380. *
  381. * @var array
  382. */
  383. protected $accessMapping = array();
  384. /**
  385. * The class name managed by the admin class.
  386. *
  387. * @var string
  388. */
  389. private $class;
  390. /**
  391. * The subclasses supported by the admin class.
  392. *
  393. * @var array
  394. */
  395. private $subClasses = array();
  396. /**
  397. * The list collection.
  398. *
  399. * @var array
  400. */
  401. private $list;
  402. /**
  403. * @var FieldDescriptionCollection
  404. */
  405. private $show;
  406. /**
  407. * @var Form
  408. */
  409. private $form;
  410. /**
  411. * @var DatagridInterface
  412. */
  413. private $filter;
  414. /**
  415. * The cached base route name.
  416. *
  417. * @var string
  418. */
  419. private $cachedBaseRouteName;
  420. /**
  421. * The cached base route pattern.
  422. *
  423. * @var string
  424. */
  425. private $cachedBaseRoutePattern;
  426. /**
  427. * The form group disposition.
  428. *
  429. * @var array|bool
  430. */
  431. private $formGroups = false;
  432. /**
  433. * The form tabs disposition.
  434. *
  435. * @var array|bool
  436. */
  437. private $formTabs = false;
  438. /**
  439. * The view group disposition.
  440. *
  441. * @var array|bool
  442. */
  443. private $showGroups = false;
  444. /**
  445. * The view tab disposition.
  446. *
  447. * @var array|bool
  448. */
  449. private $showTabs = false;
  450. /**
  451. * The manager type to use for the admin.
  452. *
  453. * @var string
  454. */
  455. private $managerType;
  456. /**
  457. * The breadcrumbsBuilder component.
  458. *
  459. * @var BreadcrumbsBuilderInterface
  460. */
  461. private $breadcrumbsBuilder;
  462. /**
  463. * @param string $code
  464. * @param string $class
  465. * @param string $baseControllerName
  466. */
  467. public function __construct($code, $class, $baseControllerName)
  468. {
  469. $this->code = $code;
  470. $this->class = $class;
  471. $this->baseControllerName = $baseControllerName;
  472. $this->predefinePerPageOptions();
  473. $this->datagridValues['_per_page'] = $this->maxPerPage;
  474. }
  475. /**
  476. * {@inheritdoc}
  477. */
  478. public function getExportFormats()
  479. {
  480. return array(
  481. 'json', 'xml', 'csv', 'xls',
  482. );
  483. }
  484. /**
  485. * @return array
  486. */
  487. public function getExportFields()
  488. {
  489. $fields = $this->getModelManager()->getExportFields($this->getClass());
  490. foreach ($this->getExtensions() as $extension) {
  491. if (method_exists($extension, 'configureExportFields')) {
  492. $fields = $extension->configureExportFields($this, $fields);
  493. }
  494. }
  495. return $fields;
  496. }
  497. /**
  498. * {@inheritdoc}
  499. */
  500. public function getDataSourceIterator()
  501. {
  502. $datagrid = $this->getDatagrid();
  503. $datagrid->buildPager();
  504. return $this->getModelManager()->getDataSourceIterator($datagrid, $this->getExportFields());
  505. }
  506. /**
  507. * {@inheritdoc}
  508. */
  509. public function validate(ErrorElement $errorElement, $object)
  510. {
  511. }
  512. /**
  513. * define custom variable.
  514. */
  515. public function initialize()
  516. {
  517. if (!$this->classnameLabel) {
  518. $this->classnameLabel = substr($this->getClass(), strrpos($this->getClass(), '\\') + 1);
  519. }
  520. $this->baseCodeRoute = $this->getCode();
  521. $this->configure();
  522. }
  523. /**
  524. * {@inheritdoc}
  525. */
  526. public function configure()
  527. {
  528. }
  529. /**
  530. * {@inheritdoc}
  531. */
  532. public function update($object)
  533. {
  534. $this->preUpdate($object);
  535. foreach ($this->extensions as $extension) {
  536. $extension->preUpdate($this, $object);
  537. }
  538. $result = $this->getModelManager()->update($object);
  539. // BC compatibility
  540. if (null !== $result) {
  541. $object = $result;
  542. }
  543. $this->postUpdate($object);
  544. foreach ($this->extensions as $extension) {
  545. $extension->postUpdate($this, $object);
  546. }
  547. return $object;
  548. }
  549. /**
  550. * {@inheritdoc}
  551. */
  552. public function create($object)
  553. {
  554. $this->prePersist($object);
  555. foreach ($this->extensions as $extension) {
  556. $extension->prePersist($this, $object);
  557. }
  558. $result = $this->getModelManager()->create($object);
  559. // BC compatibility
  560. if (null !== $result) {
  561. $object = $result;
  562. }
  563. $this->postPersist($object);
  564. foreach ($this->extensions as $extension) {
  565. $extension->postPersist($this, $object);
  566. }
  567. $this->createObjectSecurity($object);
  568. return $object;
  569. }
  570. /**
  571. * {@inheritdoc}
  572. */
  573. public function delete($object)
  574. {
  575. $this->preRemove($object);
  576. foreach ($this->extensions as $extension) {
  577. $extension->preRemove($this, $object);
  578. }
  579. $this->getSecurityHandler()->deleteObjectSecurity($this, $object);
  580. $this->getModelManager()->delete($object);
  581. $this->postRemove($object);
  582. foreach ($this->extensions as $extension) {
  583. $extension->postRemove($this, $object);
  584. }
  585. }
  586. /**
  587. * {@inheritdoc}
  588. */
  589. public function preValidate($object)
  590. {
  591. }
  592. /**
  593. * {@inheritdoc}
  594. */
  595. public function preUpdate($object)
  596. {
  597. }
  598. /**
  599. * {@inheritdoc}
  600. */
  601. public function postUpdate($object)
  602. {
  603. }
  604. /**
  605. * {@inheritdoc}
  606. */
  607. public function prePersist($object)
  608. {
  609. }
  610. /**
  611. * {@inheritdoc}
  612. */
  613. public function postPersist($object)
  614. {
  615. }
  616. /**
  617. * {@inheritdoc}
  618. */
  619. public function preRemove($object)
  620. {
  621. }
  622. /**
  623. * {@inheritdoc}
  624. */
  625. public function postRemove($object)
  626. {
  627. }
  628. /**
  629. * {@inheritdoc}
  630. */
  631. public function preBatchAction($actionName, ProxyQueryInterface $query, array &$idx, $allElements)
  632. {
  633. }
  634. /**
  635. * {@inheritdoc}
  636. */
  637. public function getFilterParameters()
  638. {
  639. $parameters = array();
  640. // build the values array
  641. if ($this->hasRequest()) {
  642. $filters = $this->request->query->get('filter', array());
  643. // if persisting filters, save filters to session, or pull them out of session if no new filters set
  644. if ($this->persistFilters) {
  645. if ($filters == array() && $this->request->query->get('filters') != 'reset') {
  646. $filters = $this->request->getSession()->get($this->getCode().'.filter.parameters', array());
  647. } else {
  648. $this->request->getSession()->set($this->getCode().'.filter.parameters', $filters);
  649. }
  650. }
  651. $parameters = array_merge(
  652. $this->getModelManager()->getDefaultSortValues($this->getClass()),
  653. $this->datagridValues,
  654. $filters
  655. );
  656. if (!$this->determinedPerPageValue($parameters['_per_page'])) {
  657. $parameters['_per_page'] = $this->maxPerPage;
  658. }
  659. // always force the parent value
  660. if ($this->isChild() && $this->getParentAssociationMapping()) {
  661. $name = str_replace('.', '__', $this->getParentAssociationMapping());
  662. $parameters[$name] = array('value' => $this->request->get($this->getParent()->getIdParameter()));
  663. }
  664. }
  665. return $parameters;
  666. }
  667. /**
  668. * {@inheritdoc}
  669. */
  670. public function buildDatagrid()
  671. {
  672. if ($this->datagrid) {
  673. return;
  674. }
  675. $filterParameters = $this->getFilterParameters();
  676. // transform _sort_by from a string to a FieldDescriptionInterface for the datagrid.
  677. if (isset($filterParameters['_sort_by']) && is_string($filterParameters['_sort_by'])) {
  678. if ($this->hasListFieldDescription($filterParameters['_sort_by'])) {
  679. $filterParameters['_sort_by'] = $this->getListFieldDescription($filterParameters['_sort_by']);
  680. } else {
  681. $filterParameters['_sort_by'] = $this->getModelManager()->getNewFieldDescriptionInstance(
  682. $this->getClass(),
  683. $filterParameters['_sort_by'],
  684. array()
  685. );
  686. $this->getListBuilder()->buildField(null, $filterParameters['_sort_by'], $this);
  687. }
  688. }
  689. // initialize the datagrid
  690. $this->datagrid = $this->getDatagridBuilder()->getBaseDatagrid($this, $filterParameters);
  691. $this->datagrid->getPager()->setMaxPageLinks($this->maxPageLinks);
  692. $mapper = new DatagridMapper($this->getDatagridBuilder(), $this->datagrid, $this);
  693. // build the datagrid filter
  694. $this->configureDatagridFilters($mapper);
  695. // ok, try to limit to add parent filter
  696. if ($this->isChild() && $this->getParentAssociationMapping() && !$mapper->has($this->getParentAssociationMapping())) {
  697. $mapper->add($this->getParentAssociationMapping(), null, array(
  698. 'show_filter' => false,
  699. 'label' => false,
  700. 'field_type' => 'sonata_type_model_hidden',
  701. 'field_options' => array(
  702. 'model_manager' => $this->getModelManager(),
  703. ),
  704. 'operator_type' => 'hidden',
  705. ), null, null, array(
  706. 'admin_code' => $this->getParent()->getCode(),
  707. ));
  708. }
  709. foreach ($this->getExtensions() as $extension) {
  710. $extension->configureDatagridFilters($mapper);
  711. }
  712. }
  713. /**
  714. * Returns the name of the parent related field, so the field can be use to set the default
  715. * value (ie the parent object) or to filter the object.
  716. *
  717. * @return string the name of the parent related field
  718. */
  719. public function getParentAssociationMapping()
  720. {
  721. return $this->parentAssociationMapping;
  722. }
  723. /**
  724. * Returns the baseRoutePattern used to generate the routing information.
  725. *
  726. * @throws \RuntimeException
  727. *
  728. * @return string the baseRoutePattern used to generate the routing information
  729. */
  730. public function getBaseRoutePattern()
  731. {
  732. if (null !== $this->cachedBaseRoutePattern) {
  733. return $this->cachedBaseRoutePattern;
  734. }
  735. if ($this->isChild()) { // the admin class is a child, prefix it with the parent route pattern
  736. if (!$this->baseRoutePattern) {
  737. preg_match(self::CLASS_REGEX, $this->class, $matches);
  738. if (!$matches) {
  739. throw new \RuntimeException(sprintf('Please define a default `baseRoutePattern` value for the admin class `%s`', get_class($this)));
  740. }
  741. }
  742. $this->cachedBaseRoutePattern = sprintf('%s/{id}/%s',
  743. $this->getParent()->getBaseRoutePattern(),
  744. $this->baseRoutePattern ?: $this->urlize($matches[5], '-')
  745. );
  746. } elseif ($this->baseRoutePattern) {
  747. $this->cachedBaseRoutePattern = $this->baseRoutePattern;
  748. } else {
  749. preg_match(self::CLASS_REGEX, $this->class, $matches);
  750. if (!$matches) {
  751. throw new \RuntimeException(sprintf('Please define a default `baseRoutePattern` value for the admin class `%s`', get_class($this)));
  752. }
  753. $this->cachedBaseRoutePattern = sprintf('/%s%s/%s',
  754. empty($matches[1]) ? '' : $this->urlize($matches[1], '-').'/',
  755. $this->urlize($matches[3], '-'),
  756. $this->urlize($matches[5], '-')
  757. );
  758. }
  759. return $this->cachedBaseRoutePattern;
  760. }
  761. /**
  762. * Returns the baseRouteName used to generate the routing information.
  763. *
  764. * @throws \RuntimeException
  765. *
  766. * @return string the baseRouteName used to generate the routing information
  767. */
  768. public function getBaseRouteName()
  769. {
  770. if (null !== $this->cachedBaseRouteName) {
  771. return $this->cachedBaseRouteName;
  772. }
  773. if ($this->isChild()) { // the admin class is a child, prefix it with the parent route name
  774. if (!$this->baseRouteName) {
  775. preg_match(self::CLASS_REGEX, $this->class, $matches);
  776. if (!$matches) {
  777. throw new \RuntimeException(sprintf('Cannot automatically determine base route name, please define a default `baseRouteName` value for the admin class `%s`', get_class($this)));
  778. }
  779. }
  780. $this->cachedBaseRouteName = sprintf('%s_%s',
  781. $this->getParent()->getBaseRouteName(),
  782. $this->baseRouteName ?: $this->urlize($matches[5])
  783. );
  784. } elseif ($this->baseRouteName) {
  785. $this->cachedBaseRouteName = $this->baseRouteName;
  786. } else {
  787. preg_match(self::CLASS_REGEX, $this->class, $matches);
  788. if (!$matches) {
  789. throw new \RuntimeException(sprintf('Cannot automatically determine base route name, please define a default `baseRouteName` value for the admin class `%s`', get_class($this)));
  790. }
  791. $this->cachedBaseRouteName = sprintf('admin_%s%s_%s',
  792. empty($matches[1]) ? '' : $this->urlize($matches[1]).'_',
  793. $this->urlize($matches[3]),
  794. $this->urlize($matches[5])
  795. );
  796. }
  797. return $this->cachedBaseRouteName;
  798. }
  799. /**
  800. * urlize the given word.
  801. *
  802. * @param string $word
  803. * @param string $sep the separator
  804. *
  805. * @return string
  806. */
  807. public function urlize($word, $sep = '_')
  808. {
  809. return strtolower(preg_replace('/[^a-z0-9_]/i', $sep.'$1', $word));
  810. }
  811. /**
  812. * {@inheritdoc}
  813. */
  814. public function getClass()
  815. {
  816. // see https://github.com/sonata-project/SonataCoreBundle/commit/247eeb0a7ca7211142e101754769d70bc402a5b4
  817. if ($this->hasSubject() && is_object($this->getSubject())) {
  818. return ClassUtils::getClass($this->getSubject());
  819. }
  820. if (!$this->hasActiveSubClass()) {
  821. if (count($this->getSubClasses()) > 0) {
  822. $subject = $this->getSubject();
  823. if ($subject && is_object($subject)) {
  824. return ClassUtils::getClass($subject);
  825. }
  826. }
  827. return $this->class;
  828. }
  829. if ($this->getParentFieldDescription() && $this->hasActiveSubClass()) {
  830. throw new \RuntimeException('Feature not implemented: an embedded admin cannot have subclass');
  831. }
  832. $subClass = $this->getRequest()->query->get('subclass');
  833. return $this->getSubClass($subClass);
  834. }
  835. /**
  836. * {@inheritdoc}
  837. */
  838. public function getSubClasses()
  839. {
  840. return $this->subClasses;
  841. }
  842. /**
  843. * {@inheritdoc}
  844. */
  845. public function addSubClass($subClass)
  846. {
  847. if (!in_array($subClass, $this->subClasses)) {
  848. $this->subClasses[] = $subClass;
  849. }
  850. }
  851. /**
  852. * {@inheritdoc}
  853. */
  854. public function setSubClasses(array $subClasses)
  855. {
  856. $this->subClasses = $subClasses;
  857. }
  858. /**
  859. * {@inheritdoc}
  860. */
  861. public function hasSubClass($name)
  862. {
  863. return isset($this->subClasses[$name]);
  864. }
  865. /**
  866. * {@inheritdoc}
  867. */
  868. public function hasActiveSubClass()
  869. {
  870. if (count($this->subClasses) > 0 && $this->request) {
  871. return null !== $this->getRequest()->query->get('subclass');
  872. }
  873. return false;
  874. }
  875. /**
  876. * {@inheritdoc}
  877. */
  878. public function getActiveSubClass()
  879. {
  880. if (!$this->hasActiveSubClass()) {
  881. return;
  882. }
  883. return $this->getClass();
  884. }
  885. /**
  886. * {@inheritdoc}
  887. */
  888. public function getActiveSubclassCode()
  889. {
  890. if (!$this->hasActiveSubClass()) {
  891. return;
  892. }
  893. $subClass = $this->getRequest()->query->get('subclass');
  894. if (!$this->hasSubClass($subClass)) {
  895. return;
  896. }
  897. return $subClass;
  898. }
  899. /**
  900. * {@inheritdoc}
  901. */
  902. public function getBatchActions()
  903. {
  904. $actions = array();
  905. if ($this->hasRoute('delete') && $this->isGranted('DELETE')) {
  906. $actions['delete'] = array(
  907. 'label' => 'action_delete',
  908. 'translation_domain' => 'SonataAdminBundle',
  909. 'ask_confirmation' => true, // by default always true
  910. );
  911. }
  912. $actions = $this->configureBatchActions($actions);
  913. foreach ($this->getExtensions() as $extension) {
  914. // TODO: remove method check in next major release
  915. if (method_exists($extension, 'configureBatchActions')) {
  916. $actions = $extension->configureBatchActions($this, $actions);
  917. }
  918. }
  919. return $actions;
  920. }
  921. /**
  922. * {@inheritdoc}
  923. */
  924. public function getRoutes()
  925. {
  926. $this->buildRoutes();
  927. return $this->routes;
  928. }
  929. /**
  930. * {@inheritdoc}
  931. */
  932. public function getRouterIdParameter()
  933. {
  934. return $this->isChild() ? '{childId}' : '{id}';
  935. }
  936. /**
  937. * {@inheritdoc}
  938. */
  939. public function getIdParameter()
  940. {
  941. return $this->isChild() ? 'childId' : 'id';
  942. }
  943. /**
  944. * {@inheritdoc}
  945. */
  946. public function hasRoute($name)
  947. {
  948. if (!$this->routeGenerator) {
  949. throw new \RuntimeException('RouteGenerator cannot be null');
  950. }
  951. return $this->routeGenerator->hasAdminRoute($this, $name);
  952. }
  953. /**
  954. * {@inheritdoc}
  955. */
  956. public function isCurrentRoute($name, $adminCode = null)
  957. {
  958. if (!$this->hasRequest()) {
  959. return false;
  960. }
  961. $request = $this->getRequest();
  962. $route = $request->get('_route');
  963. if ($adminCode) {
  964. $admin = $this->getConfigurationPool()->getAdminByAdminCode($adminCode);
  965. } else {
  966. $admin = $this;
  967. }
  968. if (!$admin) {
  969. return false;
  970. }
  971. return ($admin->getBaseRouteName().'_'.$name) == $route;
  972. }
  973. /**
  974. * {@inheritdoc}
  975. */
  976. public function generateObjectUrl($name, $object, array $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
  977. {
  978. $parameters['id'] = $this->getUrlsafeIdentifier($object);
  979. return $this->generateUrl($name, $parameters, $absolute);
  980. }
  981. /**
  982. * {@inheritdoc}
  983. */
  984. public function generateUrl($name, array $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
  985. {
  986. return $this->routeGenerator->generateUrl($this, $name, $parameters, $absolute);
  987. }
  988. /**
  989. * {@inheritdoc}
  990. */
  991. public function generateMenuUrl($name, array $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
  992. {
  993. return $this->routeGenerator->generateMenuUrl($this, $name, $parameters, $absolute);
  994. }
  995. /**
  996. * @param array $templates
  997. */
  998. public function setTemplates(array $templates)
  999. {
  1000. $this->templates = $templates;
  1001. }
  1002. /**
  1003. * @param string $name
  1004. * @param string $template
  1005. */
  1006. public function setTemplate($name, $template)
  1007. {
  1008. $this->templates[$name] = $template;
  1009. }
  1010. /**
  1011. * @return array
  1012. */
  1013. public function getTemplates()
  1014. {
  1015. return $this->templates;
  1016. }
  1017. /**
  1018. * {@inheritdoc}
  1019. */
  1020. public function getTemplate($name)
  1021. {
  1022. if (isset($this->templates[$name])) {
  1023. return $this->templates[$name];
  1024. }
  1025. }
  1026. /**
  1027. * {@inheritdoc}
  1028. */
  1029. public function getNewInstance()
  1030. {
  1031. $object = $this->getModelManager()->getModelInstance($this->getClass());
  1032. foreach ($this->getExtensions() as $extension) {
  1033. $extension->alterNewInstance($this, $object);
  1034. }
  1035. return $object;
  1036. }
  1037. /**
  1038. * {@inheritdoc}
  1039. */
  1040. public function getFormBuilder()
  1041. {
  1042. $this->formOptions['data_class'] = $this->getClass();
  1043. $formBuilder = $this->getFormContractor()->getFormBuilder(
  1044. $this->getUniqid(),
  1045. $this->formOptions
  1046. );
  1047. $this->defineFormBuilder($formBuilder);
  1048. return $formBuilder;
  1049. }
  1050. /**
  1051. * This method is being called by the main admin class and the child class,
  1052. * the getFormBuilder is only call by the main admin class.
  1053. *
  1054. * @param FormBuilderInterface $formBuilder
  1055. */
  1056. public function defineFormBuilder(FormBuilderInterface $formBuilder)
  1057. {
  1058. $mapper = new FormMapper($this->getFormContractor(), $formBuilder, $this);
  1059. $this->configureFormFields($mapper);
  1060. foreach ($this->getExtensions() as $extension) {
  1061. $extension->configureFormFields($mapper);
  1062. }
  1063. $this->attachInlineValidator();
  1064. }
  1065. /**
  1066. * {@inheritdoc}
  1067. */
  1068. public function attachAdminClass(FieldDescriptionInterface $fieldDescription)
  1069. {
  1070. $pool = $this->getConfigurationPool();
  1071. $adminCode = $fieldDescription->getOption('admin_code');
  1072. if ($adminCode !== null) {
  1073. $admin = $pool->getAdminByAdminCode($adminCode);
  1074. } else {
  1075. $admin = $pool->getAdminByClass($fieldDescription->getTargetEntity());
  1076. }
  1077. if (!$admin) {
  1078. return;
  1079. }
  1080. if ($this->hasRequest()) {
  1081. $admin->setRequest($this->getRequest());
  1082. }
  1083. $fieldDescription->setAssociationAdmin($admin);
  1084. }
  1085. /**
  1086. * {@inheritdoc}
  1087. */
  1088. public function getObject($id)
  1089. {
  1090. $object = $this->getModelManager()->find($this->getClass(), $id);
  1091. foreach ($this->getExtensions() as $extension) {
  1092. $extension->alterObject($this, $object);
  1093. }
  1094. return $object;
  1095. }
  1096. /**
  1097. * {@inheritdoc}
  1098. */
  1099. public function getForm()
  1100. {
  1101. $this->buildForm();
  1102. return $this->form;
  1103. }
  1104. /**
  1105. * {@inheritdoc}
  1106. */
  1107. public function getList()
  1108. {
  1109. $this->buildList();
  1110. return $this->list;
  1111. }
  1112. /**
  1113. * {@inheritdoc}
  1114. */
  1115. public function createQuery($context = 'list')
  1116. {
  1117. if (func_num_args() > 0) {
  1118. @trigger_error(
  1119. 'The $context argument of '.__METHOD__.' is deprecated since 3.3, to be removed in 4.0.',
  1120. E_USER_DEPRECATED
  1121. );
  1122. }
  1123. $query = $this->getModelManager()->createQuery($this->class);
  1124. foreach ($this->extensions as $extension) {
  1125. $extension->configureQuery($this, $query, $context);
  1126. }
  1127. return $query;
  1128. }
  1129. /**
  1130. * {@inheritdoc}
  1131. */
  1132. public function getDatagrid()
  1133. {
  1134. $this->buildDatagrid();
  1135. return $this->datagrid;
  1136. }
  1137. /**
  1138. * {@inheritdoc}
  1139. */
  1140. public function buildTabMenu($action, AdminInterface $childAdmin = null)
  1141. {
  1142. if ($this->loaded['tab_menu']) {
  1143. return;
  1144. }
  1145. $this->loaded['tab_menu'] = true;
  1146. $menu = $this->menuFactory->createItem('root');
  1147. $menu->setChildrenAttribute('class', 'nav navbar-nav');
  1148. $menu->setExtra('translation_domain', $this->translationDomain);
  1149. // Prevents BC break with KnpMenuBundle v1.x
  1150. if (method_exists($menu, 'setCurrentUri')) {
  1151. $menu->setCurrentUri($this->getRequest()->getBaseUrl().$this->getRequest()->getPathInfo());
  1152. }
  1153. $this->configureTabMenu($menu, $action, $childAdmin);
  1154. foreach ($this->getExtensions() as $extension) {
  1155. $extension->configureTabMenu($this, $menu, $action, $childAdmin);
  1156. }
  1157. $this->menu = $menu;
  1158. }
  1159. /**
  1160. * {@inheritdoc}
  1161. */
  1162. public function buildSideMenu($action, AdminInterface $childAdmin = null)
  1163. {
  1164. return $this->buildTabMenu($action, $childAdmin);
  1165. }
  1166. /**
  1167. * @param string $action
  1168. * @param AdminInterface $childAdmin
  1169. *
  1170. * @return ItemInterface
  1171. */
  1172. public function getSideMenu($action, AdminInterface $childAdmin = null)
  1173. {
  1174. if ($this->isChild()) {
  1175. return $this->getParent()->getSideMenu($action, $this);
  1176. }
  1177. $this->buildSideMenu($action, $childAdmin);
  1178. return $this->menu;
  1179. }
  1180. /**
  1181. * Returns the root code.
  1182. *
  1183. * @return string the root code
  1184. */
  1185. public function getRootCode()
  1186. {
  1187. return $this->getRoot()->getCode();
  1188. }
  1189. /**
  1190. * Returns the master admin.
  1191. *
  1192. * @return Admin the root admin class
  1193. */
  1194. public function getRoot()
  1195. {
  1196. $parentFieldDescription = $this->getParentFieldDescription();
  1197. if (!$parentFieldDescription) {
  1198. return $this;
  1199. }
  1200. return $parentFieldDescription->getAdmin()->getRoot();
  1201. }
  1202. /**
  1203. * {@inheritdoc}
  1204. */
  1205. public function setBaseControllerName($baseControllerName)
  1206. {
  1207. $this->baseControllerName = $baseControllerName;
  1208. }
  1209. /**
  1210. * {@inheritdoc}
  1211. */
  1212. public function getBaseControllerName()
  1213. {
  1214. return $this->baseControllerName;
  1215. }
  1216. /**
  1217. * @param string $label
  1218. */
  1219. public function setLabel($label)
  1220. {
  1221. $this->label = $label;
  1222. }
  1223. /**
  1224. * {@inheritdoc}
  1225. */
  1226. public function getLabel()
  1227. {
  1228. return $this->label;
  1229. }
  1230. /**
  1231. * @param bool $persist
  1232. */
  1233. public function setPersistFilters($persist)
  1234. {
  1235. $this->persistFilters = $persist;
  1236. }
  1237. /**
  1238. * @param int $maxPerPage
  1239. */
  1240. public function setMaxPerPage($maxPerPage)
  1241. {
  1242. $this->maxPerPage = $maxPerPage;
  1243. }
  1244. /**
  1245. * @return int
  1246. */
  1247. public function getMaxPerPage()
  1248. {
  1249. return $this->maxPerPage;
  1250. }
  1251. /**
  1252. * @param int $maxPageLinks
  1253. */
  1254. public function setMaxPageLinks($maxPageLinks)
  1255. {
  1256. $this->maxPageLinks = $maxPageLinks;
  1257. }
  1258. /**
  1259. * @return int
  1260. */
  1261. public function getMaxPageLinks()
  1262. {
  1263. return $this->maxPageLinks;
  1264. }
  1265. /**
  1266. * {@inheritdoc}
  1267. */
  1268. public function getFormGroups()
  1269. {
  1270. return $this->formGroups;
  1271. }
  1272. /**
  1273. * {@inheritdoc}
  1274. */
  1275. public function setFormGroups(array $formGroups)
  1276. {
  1277. $this->formGroups = $formGroups;
  1278. }
  1279. /**
  1280. * {@inheritdoc}
  1281. */
  1282. public function removeFieldFromFormGroup($key)
  1283. {
  1284. foreach ($this->formGroups as $name => $formGroup) {
  1285. unset($this->formGroups[$name]['fields'][$key]);
  1286. if (empty($this->formGroups[$name]['fields'])) {
  1287. unset($this->formGroups[$name]);
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * @param array $group
  1293. * @param array $keys
  1294. */
  1295. public function reorderFormGroup($group, array $keys)
  1296. {
  1297. $formGroups = $this->getFormGroups();
  1298. $formGroups[$group]['fields'] = array_merge(array_flip($keys), $formGroups[$group]['fields']);
  1299. $this->setFormGroups($formGroups);
  1300. }
  1301. /**
  1302. * {@inheritdoc}
  1303. */
  1304. public function getFormTabs()
  1305. {
  1306. return $this->formTabs;
  1307. }
  1308. /**
  1309. * {@inheritdoc}
  1310. */
  1311. public function setFormTabs(array $formTabs)
  1312. {
  1313. $this->formTabs = $formTabs;
  1314. }
  1315. /**
  1316. * {@inheritdoc}
  1317. */
  1318. public function getShowTabs()
  1319. {
  1320. return $this->showTabs;
  1321. }
  1322. /**
  1323. * {@inheritdoc}
  1324. */
  1325. public function setShowTabs(array $showTabs)
  1326. {
  1327. $this->showTabs = $showTabs;
  1328. }
  1329. /**
  1330. * {@inheritdoc}
  1331. */
  1332. public function getShowGroups()
  1333. {
  1334. return $this->showGroups;
  1335. }
  1336. /**
  1337. * {@inheritdoc}
  1338. */
  1339. public function setShowGroups(array $showGroups)
  1340. {
  1341. $this->showGroups = $showGroups;
  1342. }
  1343. /**
  1344. * {@inheritdoc}
  1345. */
  1346. public function reorderShowGroup($group, array $keys)
  1347. {
  1348. $showGroups = $this->getShowGroups();
  1349. $showGroups[$group]['fields'] = array_merge(array_flip($keys), $showGroups[$group]['fields']);
  1350. $this->setShowGroups($showGroups);
  1351. }
  1352. /**
  1353. * {@inheritdoc}
  1354. */
  1355. public function setParentFieldDescription(FieldDescriptionInterface $parentFieldDescription)
  1356. {
  1357. $this->parentFieldDescription = $parentFieldDescription;
  1358. }
  1359. /**
  1360. * {@inheritdoc}
  1361. */
  1362. public function getParentFieldDescription()
  1363. {
  1364. return $this->parentFieldDescription;
  1365. }
  1366. /**
  1367. * {@inheritdoc}
  1368. */
  1369. public function hasParentFieldDescription()
  1370. {
  1371. return $this->parentFieldDescription instanceof FieldDescriptionInterface;
  1372. }
  1373. /**
  1374. * {@inheritdoc}
  1375. */
  1376. public function setSubject($subject)
  1377. {
  1378. $this->subject = $subject;
  1379. }
  1380. /**
  1381. * {@inheritdoc}
  1382. */
  1383. public function getSubject()
  1384. {
  1385. if ($this->subject === null && $this->request) {
  1386. $id = $this->request->get($this->getIdParameter());
  1387. $this->subject = $this->getModelManager()->find($this->class, $id);
  1388. }
  1389. return $this->subject;
  1390. }
  1391. /**
  1392. * {@inheritdoc}
  1393. */
  1394. public function hasSubject()
  1395. {
  1396. return $this->subject != null;
  1397. }
  1398. /**
  1399. * {@inheritdoc}
  1400. */
  1401. public function getFormFieldDescriptions()
  1402. {
  1403. $this->buildForm();
  1404. return $this->formFieldDescriptions;
  1405. }
  1406. /**
  1407. * {@inheritdoc}
  1408. */
  1409. public function getFormFieldDescription($name)
  1410. {
  1411. return $this->hasFormFieldDescription($name) ? $this->formFieldDescriptions[$name] : null;
  1412. }
  1413. /**
  1414. * Returns true if the admin has a FieldDescription with the given $name.
  1415. *
  1416. * @param string $name
  1417. *
  1418. * @return bool
  1419. */
  1420. public function hasFormFieldDescription($name)
  1421. {
  1422. return array_key_exists($name, $this->formFieldDescriptions) ? true : false;
  1423. }
  1424. /**
  1425. * {@inheritdoc}
  1426. */
  1427. public function addFormFieldDescription($name, FieldDescriptionInterface $fieldDescription)
  1428. {
  1429. $this->formFieldDescriptions[$name] = $fieldDescription;
  1430. }
  1431. /**
  1432. * remove a FieldDescription.
  1433. *
  1434. * @param string $name
  1435. */
  1436. public function removeFormFieldDescription($name)
  1437. {
  1438. unset($this->formFieldDescriptions[$name]);
  1439. }
  1440. /**
  1441. * build and return the collection of form FieldDescription.
  1442. *
  1443. * @return array collection of form FieldDescription
  1444. */
  1445. public function getShowFieldDescriptions()
  1446. {
  1447. $this->buildShow();
  1448. return $this->showFieldDescriptions;
  1449. }
  1450. /**
  1451. * Returns the form FieldDescription with the given $name.
  1452. *
  1453. * @param string $name
  1454. *
  1455. * @return FieldDescriptionInterface
  1456. */
  1457. public function getShowFieldDescription($name)
  1458. {
  1459. $this->buildShow();
  1460. return $this->hasShowFieldDescription($name) ? $this->showFieldDescriptions[$name] : null;
  1461. }
  1462. /**
  1463. * {@inheritdoc}
  1464. */
  1465. public function hasShowFieldDescription($name)
  1466. {
  1467. return array_key_exists($name, $this->showFieldDescriptions);
  1468. }
  1469. /**
  1470. * {@inheritdoc}
  1471. */
  1472. public function addShowFieldDescription($name, FieldDescriptionInterface $fieldDescription)
  1473. {
  1474. $this->showFieldDescriptions[$name] = $fieldDescription;
  1475. }
  1476. /**
  1477. * {@inheritdoc}
  1478. */
  1479. public function removeShowFieldDescription($name)
  1480. {
  1481. unset($this->showFieldDescriptions[$name]);
  1482. }
  1483. /**
  1484. * {@inheritdoc}
  1485. */
  1486. public function getListFieldDescriptions()
  1487. {
  1488. $this->buildList();
  1489. return $this->listFieldDescriptions;
  1490. }
  1491. /**
  1492. * {@inheritdoc}
  1493. */
  1494. public function getListFieldDescription($name)
  1495. {
  1496. return $this->hasListFieldDescription($name) ? $this->listFieldDescriptions[$name] : null;
  1497. }
  1498. /**
  1499. * {@inheritdoc}
  1500. */
  1501. public function hasListFieldDescription($name)
  1502. {
  1503. $this->buildList();
  1504. return array_key_exists($name, $this->listFieldDescriptions) ? true : false;
  1505. }
  1506. /**
  1507. * {@inheritdoc}
  1508. */
  1509. public function addListFieldDescription($name, FieldDescriptionInterface $fieldDescription)
  1510. {
  1511. $this->listFieldDescriptions[$name] = $fieldDescription;
  1512. }
  1513. /**
  1514. * {@inheritdoc}
  1515. */
  1516. public function removeListFieldDescription($name)
  1517. {
  1518. unset($this->listFieldDescriptions[$name]);
  1519. }
  1520. /**
  1521. * {@inheritdoc}
  1522. */
  1523. public function getFilterFieldDescription($name)
  1524. {
  1525. return $this->hasFilterFieldDescription($name) ? $this->filterFieldDescriptions[$name] : null;
  1526. }
  1527. /**
  1528. * {@inheritdoc}
  1529. */
  1530. public function hasFilterFieldDescription($name)
  1531. {
  1532. return array_key_exists($name, $this->filterFieldDescriptions) ? true : false;
  1533. }
  1534. /**
  1535. * {@inheritdoc}
  1536. */
  1537. public function addFilterFieldDescription($name, FieldDescriptionInterface $fieldDescription)
  1538. {
  1539. $this->filterFieldDescriptions[$name] = $fieldDescription;
  1540. }
  1541. /**
  1542. * {@inheritdoc}
  1543. */
  1544. public function removeFilterFieldDescription($name)
  1545. {
  1546. unset($this->filterFieldDescriptions[$name]);
  1547. }
  1548. /**
  1549. * {@inheritdoc}
  1550. */
  1551. public function getFilterFieldDescriptions()
  1552. {
  1553. $this->buildDatagrid();
  1554. return $this->filterFieldDescriptions;
  1555. }
  1556. /**
  1557. * {@inheritdoc}
  1558. */
  1559. public function addChild(AdminInterface $child)
  1560. {
  1561. $this->children[$child->getCode()] = $child;
  1562. $child->setBaseCodeRoute($this->getCode().'|'.$child->getCode());
  1563. $child->setParent($this);
  1564. }
  1565. /**
  1566. * {@inheritdoc}
  1567. */
  1568. public function hasChild($code)
  1569. {
  1570. return isset($this->children[$code]);
  1571. }
  1572. /**
  1573. * {@inheritdoc}
  1574. */
  1575. public function getChildren()
  1576. {
  1577. return $this->children;
  1578. }
  1579. /**
  1580. * {@inheritdoc}
  1581. */
  1582. public function getChild($code)
  1583. {
  1584. return $this->hasChild($code) ? $this->children[$code] : null;
  1585. }
  1586. /**
  1587. * {@inheritdoc}
  1588. */
  1589. public function setParent(AdminInterface $parent)
  1590. {
  1591. $this->parent = $parent;
  1592. }
  1593. /**
  1594. * {@inheritdoc}
  1595. */
  1596. public function getParent()
  1597. {
  1598. return $this->parent;
  1599. }
  1600. /**
  1601. * {@inheritdoc}
  1602. */
  1603. public function isChild()
  1604. {
  1605. return $this->parent instanceof AdminInterface;
  1606. }
  1607. /**
  1608. * Returns true if the admin has children, false otherwise.
  1609. *
  1610. * @return bool if the admin has children
  1611. */
  1612. public function hasChildren()
  1613. {
  1614. return count($this->children) > 0;
  1615. }
  1616. /**
  1617. * {@inheritdoc}
  1618. */
  1619. public function setUniqid($uniqid)
  1620. {
  1621. $this->uniqid = $uniqid;
  1622. }
  1623. /**
  1624. * {@inheritdoc}
  1625. */
  1626. public function getUniqid()
  1627. {
  1628. if (!$this->uniqid) {
  1629. $this->uniqid = 's'.uniqid();
  1630. }
  1631. return $this->uniqid;
  1632. }
  1633. /**
  1634. * Returns the classname label.
  1635. *
  1636. * @return string the classname label
  1637. */
  1638. public function getClassnameLabel()
  1639. {
  1640. return $this->classnameLabel;
  1641. }
  1642. /**
  1643. * {@inheritdoc}
  1644. */
  1645. public function getPersistentParameters()
  1646. {
  1647. $parameters = array();
  1648. foreach ($this->getExtensions() as $extension) {
  1649. $params = $extension->getPersistentParameters($this);
  1650. if (!is_array($params)) {
  1651. throw new \RuntimeException(sprintf('The %s::getPersistentParameters must return an array', get_class($extension)));
  1652. }
  1653. $parameters = array_merge($parameters, $params);
  1654. }
  1655. return $parameters;
  1656. }
  1657. /**
  1658. * @param string $name
  1659. *
  1660. * @return null|mixed
  1661. */
  1662. public function getPersistentParameter($name)
  1663. {
  1664. $parameters = $this->getPersistentParameters();
  1665. return isset($parameters[$name]) ? $parameters[$name] : null;
  1666. }
  1667. /**
  1668. * {@inheritdoc}
  1669. */
  1670. public function getBreadcrumbs($action)
  1671. {
  1672. @trigger_error(
  1673. 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'.
  1674. ' Use Sonata\AdminBundle\Admin\BreadcrumbsBuilder::getBreadcrumbs instead.',
  1675. E_USER_DEPRECATED
  1676. );
  1677. return $this->getBreadcrumbsBuilder()->getBreadcrumbs($this, $action);
  1678. }
  1679. /**
  1680. * Generates the breadcrumbs array.
  1681. *
  1682. * Note: the method will be called by the top admin instance (parent => child)
  1683. *
  1684. * @param string $action
  1685. * @param ItemInterface|null $menu
  1686. *
  1687. * @return array
  1688. */
  1689. public function buildBreadcrumbs($action, MenuItemInterface $menu = null)
  1690. {
  1691. @trigger_error(
  1692. 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.',
  1693. E_USER_DEPRECATED
  1694. );
  1695. if (isset($this->breadcrumbs[$action])) {
  1696. return $this->breadcrumbs[$action];
  1697. }
  1698. return $this->breadcrumbs[$action] = $this->getBreadcrumbsBuilder()
  1699. ->buildBreadcrumbs($this, $action, $menu);
  1700. }
  1701. /**
  1702. * NEXT_MAJOR : remove this method.
  1703. *
  1704. * @return BreadcrumbsBuilderInterface
  1705. */
  1706. final public function getBreadcrumbsBuilder()
  1707. {
  1708. @trigger_error(
  1709. 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'.
  1710. ' Use the sonata.admin.breadcrumbs_builder service instead.',
  1711. E_USER_DEPRECATED
  1712. );
  1713. if ($this->breadcrumbsBuilder === null) {
  1714. $this->breadcrumbsBuilder = new BreadcrumbsBuilder();
  1715. }
  1716. return $this->breadcrumbsBuilder;
  1717. }
  1718. /**
  1719. * NEXT_MAJOR : remove this method.
  1720. *
  1721. * @param BreadcrumbsBuilderInterface
  1722. *
  1723. * @return AbstractAdmin
  1724. */
  1725. final public function setBreadcrumbsBuilder(BreadcrumbsBuilderInterface $value)
  1726. {
  1727. @trigger_error(
  1728. 'The '.__METHOD__.' method is deprecated since version 3.2 and will be removed in 4.0.'.
  1729. ' Use the sonata.admin.breadcrumbs_builder service instead.',
  1730. E_USER_DEPRECATED
  1731. );
  1732. $this->breadcrumbsBuilder = $value;
  1733. return $this;
  1734. }
  1735. /**
  1736. * {@inheritdoc}
  1737. */
  1738. public function setCurrentChild($currentChild)
  1739. {
  1740. $this->currentChild = $currentChild;
  1741. }
  1742. /**
  1743. * {@inheritdoc}
  1744. */
  1745. public function getCurrentChild()
  1746. {
  1747. return $this->currentChild;
  1748. }
  1749. /**
  1750. * Returns the current child admin instance.
  1751. *
  1752. * @return AdminInterface|null the current child admin instance
  1753. */
  1754. public function getCurrentChildAdmin()
  1755. {
  1756. foreach ($this->children as $children) {
  1757. if ($children->getCurrentChild()) {
  1758. return $children;
  1759. }
  1760. }
  1761. return;
  1762. }
  1763. /**
  1764. * {@inheritdoc}
  1765. */
  1766. public function trans($id, array $parameters = array(), $domain = null, $locale = null)
  1767. {
  1768. $domain = $domain ?: $this->getTranslationDomain();
  1769. if (!$this->translator) {
  1770. return $id;
  1771. }
  1772. return $this->translator->trans($id, $parameters, $domain, $locale);
  1773. }
  1774. /**
  1775. * Translate a message id.
  1776. *
  1777. * @param string $id
  1778. * @param int $count
  1779. * @param array $parameters
  1780. * @param string|null $domain
  1781. * @param string|null $locale
  1782. *
  1783. * @return string the translated string
  1784. */
  1785. public function transChoice($id, $count, array $parameters = array(), $domain = null, $locale = null)
  1786. {
  1787. $domain = $domain ?: $this->getTranslationDomain();
  1788. if (!$this->translator) {
  1789. return $id;
  1790. }
  1791. return $this->translator->transChoice($id, $count, $parameters, $domain, $locale);
  1792. }
  1793. /**
  1794. * {@inheritdoc}
  1795. */
  1796. public function setTranslationDomain($translationDomain)
  1797. {
  1798. $this->translationDomain = $translationDomain;
  1799. }
  1800. /**
  1801. * {@inheritdoc}
  1802. */
  1803. public function getTranslationDomain()
  1804. {
  1805. return $this->translationDomain;
  1806. }
  1807. /**
  1808. * {@inheritdoc}
  1809. */
  1810. public function setTranslator(TranslatorInterface $translator)
  1811. {
  1812. $this->translator = $translator;
  1813. }
  1814. /**
  1815. * {@inheritdoc}
  1816. */
  1817. public function getTranslator()
  1818. {
  1819. return $this->translator;
  1820. }
  1821. /**
  1822. * {@inheritdoc}
  1823. */
  1824. public function getTranslationLabel($label, $context = '', $type = '')
  1825. {
  1826. return $this->getLabelTranslatorStrategy()->getLabel($label, $context, $type);
  1827. }
  1828. /**
  1829. * {@inheritdoc}
  1830. */
  1831. public function setRequest(Request $request)
  1832. {
  1833. $this->request = $request;
  1834. foreach ($this->getChildren() as $children) {
  1835. $children->setRequest($request);
  1836. }
  1837. }
  1838. /**
  1839. * {@inheritdoc}
  1840. */
  1841. public function getRequest()
  1842. {
  1843. if (!$this->request) {
  1844. throw new \RuntimeException('The Request object has not been set');
  1845. }
  1846. return $this->request;
  1847. }
  1848. /**
  1849. * {@inheritdoc}
  1850. */
  1851. public function hasRequest()
  1852. {
  1853. return $this->request !== null;
  1854. }
  1855. /**
  1856. * {@inheritdoc}
  1857. */
  1858. public function setFormContractor(FormContractorInterface $formBuilder)
  1859. {
  1860. $this->formContractor = $formBuilder;
  1861. }
  1862. /**
  1863. * @return FormContractorInterface
  1864. */
  1865. public function getFormContractor()
  1866. {
  1867. return $this->formContractor;
  1868. }
  1869. /**
  1870. * {@inheritdoc}
  1871. */
  1872. public function setDatagridBuilder(DatagridBuilderInterface $datagridBuilder)
  1873. {
  1874. $this->datagridBuilder = $datagridBuilder;
  1875. }
  1876. /**
  1877. * {@inheritdoc}
  1878. */
  1879. public function getDatagridBuilder()
  1880. {
  1881. return $this->datagridBuilder;
  1882. }
  1883. /**
  1884. * {@inheritdoc}
  1885. */
  1886. public function setListBuilder(ListBuilderInterface $listBuilder)
  1887. {
  1888. $this->listBuilder = $listBuilder;
  1889. }
  1890. /**
  1891. * {@inheritdoc}
  1892. */
  1893. public function getListBuilder()
  1894. {
  1895. return $this->listBuilder;
  1896. }
  1897. /**
  1898. * @param ShowBuilderInterface $showBuilder
  1899. */
  1900. public function setShowBuilder(ShowBuilderInterface $showBuilder)
  1901. {
  1902. $this->showBuilder = $showBuilder;
  1903. }
  1904. /**
  1905. * @return ShowBuilderInterface
  1906. */
  1907. public function getShowBuilder()
  1908. {
  1909. return $this->showBuilder;
  1910. }
  1911. /**
  1912. * {@inheritdoc}
  1913. */
  1914. public function setConfigurationPool(Pool $configurationPool)
  1915. {
  1916. $this->configurationPool = $configurationPool;
  1917. }
  1918. /**
  1919. * @return Pool
  1920. */
  1921. public function getConfigurationPool()
  1922. {
  1923. return $this->configurationPool;
  1924. }
  1925. /**
  1926. * {@inheritdoc}
  1927. */
  1928. public function setRouteGenerator(RouteGeneratorInterface $routeGenerator)
  1929. {
  1930. $this->routeGenerator = $routeGenerator;
  1931. }
  1932. /**
  1933. * @return RouteGeneratorInterface
  1934. */
  1935. public function getRouteGenerator()
  1936. {
  1937. return $this->routeGenerator;
  1938. }
  1939. /**
  1940. * {@inheritdoc}
  1941. */
  1942. public function getCode()
  1943. {
  1944. return $this->code;
  1945. }
  1946. /**
  1947. * @param string $baseCodeRoute
  1948. */
  1949. public function setBaseCodeRoute($baseCodeRoute)
  1950. {
  1951. $this->baseCodeRoute = $baseCodeRoute;
  1952. }
  1953. /**
  1954. * {@inheritdoc}
  1955. */
  1956. public function getBaseCodeRoute()
  1957. {
  1958. return $this->baseCodeRoute;
  1959. }
  1960. /**
  1961. * {@inheritdoc}
  1962. */
  1963. public function getModelManager()
  1964. {
  1965. return $this->modelManager;
  1966. }
  1967. /**
  1968. * @param ModelManagerInterface $modelManager
  1969. */
  1970. public function setModelManager(ModelManagerInterface $modelManager)
  1971. {
  1972. $this->modelManager = $modelManager;
  1973. }
  1974. /**
  1975. * {@inheritdoc}
  1976. */
  1977. public function getManagerType()
  1978. {
  1979. return $this->managerType;
  1980. }
  1981. /**
  1982. * @param string $type
  1983. */
  1984. public function setManagerType($type)
  1985. {
  1986. $this->managerType = $type;
  1987. }
  1988. /**
  1989. * {@inheritdoc}
  1990. */
  1991. public function getObjectIdentifier()
  1992. {
  1993. return $this->getCode();
  1994. }
  1995. /**
  1996. * Set the roles and permissions per role.
  1997. *
  1998. * @param array $information
  1999. */
  2000. public function setSecurityInformation(array $information)
  2001. {
  2002. $this->securityInformation = $information;
  2003. }
  2004. /**
  2005. * {@inheritdoc}
  2006. */
  2007. public function getSecurityInformation()
  2008. {
  2009. return $this->securityInformation;
  2010. }
  2011. /**
  2012. * Return the list of permissions the user should have in order to display the admin.
  2013. *
  2014. * @param string $context
  2015. *
  2016. * @return array
  2017. */
  2018. public function getPermissionsShow($context)
  2019. {
  2020. switch ($context) {
  2021. case self::CONTEXT_DASHBOARD:
  2022. case self::CONTEXT_MENU:
  2023. default:
  2024. return array('LIST');
  2025. }
  2026. }
  2027. /**
  2028. * {@inheritdoc}
  2029. */
  2030. public function showIn($context)
  2031. {
  2032. switch ($context) {
  2033. case self::CONTEXT_DASHBOARD:
  2034. case self::CONTEXT_MENU:
  2035. default:
  2036. return $this->isGranted($this->getPermissionsShow($context));
  2037. }
  2038. }
  2039. /**
  2040. * {@inheritdoc}
  2041. */
  2042. public function createObjectSecurity($object)
  2043. {
  2044. $this->getSecurityHandler()->createObjectSecurity($this, $object);
  2045. }
  2046. /**
  2047. * {@inheritdoc}
  2048. */
  2049. public function setSecurityHandler(SecurityHandlerInterface $securityHandler)
  2050. {
  2051. $this->securityHandler = $securityHandler;
  2052. }
  2053. /**
  2054. * {@inheritdoc}
  2055. */
  2056. public function getSecurityHandler()
  2057. {
  2058. return $this->securityHandler;
  2059. }
  2060. /**
  2061. * {@inheritdoc}
  2062. */
  2063. public function isGranted($name, $object = null)
  2064. {
  2065. $key = md5(json_encode($name).($object ? '/'.spl_object_hash($object) : ''));
  2066. if (!array_key_exists($key, $this->cacheIsGranted)) {
  2067. $this->cacheIsGranted[$key] = $this->securityHandler->isGranted($this, $name, $object ?: $this);
  2068. }
  2069. return $this->cacheIsGranted[$key];
  2070. }
  2071. /**
  2072. * {@inheritdoc}
  2073. */
  2074. public function getUrlsafeIdentifier($entity)
  2075. {
  2076. return $this->getModelManager()->getUrlsafeIdentifier($entity);
  2077. }
  2078. /**
  2079. * {@inheritdoc}
  2080. */
  2081. public function getNormalizedIdentifier($entity)
  2082. {
  2083. return $this->getModelManager()->getNormalizedIdentifier($entity);
  2084. }
  2085. /**
  2086. * {@inheritdoc}
  2087. */
  2088. public function id($entity)
  2089. {
  2090. return $this->getNormalizedIdentifier($entity);
  2091. }
  2092. /**
  2093. * {@inheritdoc}
  2094. */
  2095. public function setValidator($validator)
  2096. {
  2097. // TODO: Remove it when bumping requirements to SF 2.5+
  2098. if (!$validator instanceof ValidatorInterface && !$validator instanceof LegacyValidatorInterface) {
  2099. throw new \InvalidArgumentException('Argument 1 must be an instance of Symfony\Component\Validator\Validator\ValidatorInterface or Symfony\Component\Validator\ValidatorInterface');
  2100. }
  2101. $this->validator = $validator;
  2102. }
  2103. /**
  2104. * {@inheritdoc}
  2105. */
  2106. public function getValidator()
  2107. {
  2108. return $this->validator;
  2109. }
  2110. /**
  2111. * {@inheritdoc}
  2112. */
  2113. public function getShow()
  2114. {
  2115. $this->buildShow();
  2116. return $this->show;
  2117. }
  2118. /**
  2119. * {@inheritdoc}
  2120. */
  2121. public function setFormTheme(array $formTheme)
  2122. {
  2123. $this->formTheme = $formTheme;
  2124. }
  2125. /**
  2126. * {@inheritdoc}
  2127. */
  2128. public function getFormTheme()
  2129. {
  2130. return $this->formTheme;
  2131. }
  2132. /**
  2133. * {@inheritdoc}
  2134. */
  2135. public function setFilterTheme(array $filterTheme)
  2136. {
  2137. $this->filterTheme = $filterTheme;
  2138. }
  2139. /**
  2140. * {@inheritdoc}
  2141. */
  2142. public function getFilterTheme()
  2143. {
  2144. return $this->filterTheme;
  2145. }
  2146. /**
  2147. * {@inheritdoc}
  2148. */
  2149. public function addExtension(AdminExtensionInterface $extension)
  2150. {
  2151. $this->extensions[] = $extension;
  2152. }
  2153. /**
  2154. * {@inheritdoc}
  2155. */
  2156. public function getExtensions()
  2157. {
  2158. return $this->extensions;
  2159. }
  2160. /**
  2161. * {@inheritdoc}
  2162. */
  2163. public function setMenuFactory(MenuFactoryInterface $menuFactory)
  2164. {
  2165. $this->menuFactory = $menuFactory;
  2166. }
  2167. /**
  2168. * {@inheritdoc}
  2169. */
  2170. public function getMenuFactory()
  2171. {
  2172. return $this->menuFactory;
  2173. }
  2174. /**
  2175. * {@inheritdoc}
  2176. */
  2177. public function setRouteBuilder(RouteBuilderInterface $routeBuilder)
  2178. {
  2179. $this->routeBuilder = $routeBuilder;
  2180. }
  2181. /**
  2182. * {@inheritdoc}
  2183. */
  2184. public function getRouteBuilder()
  2185. {
  2186. return $this->routeBuilder;
  2187. }
  2188. /**
  2189. * {@inheritdoc}
  2190. */
  2191. public function toString($object)
  2192. {
  2193. if (!is_object($object)) {
  2194. return '';
  2195. }
  2196. if (method_exists($object, '__toString') && null !== $object->__toString()) {
  2197. return (string) $object;
  2198. }
  2199. return sprintf('%s:%s', ClassUtils::getClass($object), spl_object_hash($object));
  2200. }
  2201. /**
  2202. * {@inheritdoc}
  2203. */
  2204. public function setLabelTranslatorStrategy(LabelTranslatorStrategyInterface $labelTranslatorStrategy)
  2205. {
  2206. $this->labelTranslatorStrategy = $labelTranslatorStrategy;
  2207. }
  2208. /**
  2209. * {@inheritdoc}
  2210. */
  2211. public function getLabelTranslatorStrategy()
  2212. {
  2213. return $this->labelTranslatorStrategy;
  2214. }
  2215. /**
  2216. * {@inheritdoc}
  2217. */
  2218. public function supportsPreviewMode()
  2219. {
  2220. return $this->supportsPreviewMode;
  2221. }
  2222. /**
  2223. * Set custom per page options.
  2224. *
  2225. * @param array $options
  2226. */
  2227. public function setPerPageOptions(array $options)
  2228. {
  2229. $this->perPageOptions = $options;
  2230. }
  2231. /**
  2232. * Returns predefined per page options.
  2233. *
  2234. * @return array
  2235. */
  2236. public function getPerPageOptions()
  2237. {
  2238. return $this->perPageOptions;
  2239. }
  2240. /**
  2241. * Set pager type.
  2242. *
  2243. * @param string $pagerType
  2244. */
  2245. public function setPagerType($pagerType)
  2246. {
  2247. $this->pagerType = $pagerType;
  2248. }
  2249. /**
  2250. * Get pager type.
  2251. *
  2252. * @return string
  2253. */
  2254. public function getPagerType()
  2255. {
  2256. return $this->pagerType;
  2257. }
  2258. /**
  2259. * Returns true if the per page value is allowed, false otherwise.
  2260. *
  2261. * @param int $perPage
  2262. *
  2263. * @return bool
  2264. */
  2265. public function determinedPerPageValue($perPage)
  2266. {
  2267. return in_array($perPage, $this->perPageOptions);
  2268. }
  2269. /**
  2270. * {@inheritdoc}
  2271. */
  2272. public function isAclEnabled()
  2273. {
  2274. return $this->getSecurityHandler() instanceof AclSecurityHandlerInterface;
  2275. }
  2276. /**
  2277. * {@inheritdoc}
  2278. */
  2279. public function getObjectMetadata($object)
  2280. {
  2281. return new Metadata($this->toString($object));
  2282. }
  2283. /**
  2284. * {@inheritdoc}
  2285. */
  2286. public function getListModes()
  2287. {
  2288. return $this->listModes;
  2289. }
  2290. /**
  2291. * {@inheritdoc}
  2292. */
  2293. public function setListMode($mode)
  2294. {
  2295. if (!$this->hasRequest()) {
  2296. throw new \RuntimeException(sprintf('No request attached to the current admin: %s', $this->getCode()));
  2297. }
  2298. $this->getRequest()->getSession()->set(sprintf('%s.list_mode', $this->getCode()), $mode);
  2299. }
  2300. /**
  2301. * {@inheritdoc}
  2302. */
  2303. public function getListMode()
  2304. {
  2305. if (!$this->hasRequest()) {
  2306. return 'list';
  2307. }
  2308. return $this->getRequest()->getSession()->get(sprintf('%s.list_mode', $this->getCode()), 'list');
  2309. }
  2310. /**
  2311. * {@inheritdoc}
  2312. */
  2313. public function getAccessMapping()
  2314. {
  2315. return $this->accessMapping;
  2316. }
  2317. /**
  2318. * {@inheritdoc}
  2319. */
  2320. public function checkAccess($action, $object = null)
  2321. {
  2322. $access = $this->getAccess();
  2323. if (!array_key_exists($action, $access)) {
  2324. throw new \InvalidArgumentException(sprintf('Action "%s" could not be found in access mapping. Please make sure your action is defined into your admin class accessMapping property.', $action));
  2325. }
  2326. if (!is_array($access[$action])) {
  2327. $access[$action] = array($access[$action]);
  2328. }
  2329. foreach ($access[$action] as $role) {
  2330. if (false === $this->isGranted($role, $object)) {
  2331. throw new AccessDeniedException(sprintf('Access Denied to the action %s and role %s', $action, $role));
  2332. }
  2333. }
  2334. }
  2335. /**
  2336. * Hook to handle access authorization, without throw Exception.
  2337. *
  2338. * @param string $action
  2339. * @param object $object
  2340. *
  2341. * @return bool
  2342. */
  2343. public function hasAccess($action, $object = null)
  2344. {
  2345. $access = $this->getAccess();
  2346. if (!array_key_exists($action, $access)) {
  2347. return false;
  2348. }
  2349. if (!is_array($access[$action])) {
  2350. $access[$action] = array($access[$action]);
  2351. }
  2352. foreach ($access[$action] as $role) {
  2353. if (false === $this->isGranted($role, $object)) {
  2354. return false;
  2355. }
  2356. }
  2357. return true;
  2358. }
  2359. /**
  2360. * {@inheritdoc}
  2361. */
  2362. public function configureActionButtons($action, $object = null)
  2363. {
  2364. $list = array();
  2365. if (in_array($action, array('tree', 'show', 'edit', 'delete', 'list', 'batch'))) {
  2366. $list['create'] = array(
  2367. 'template' => 'SonataAdminBundle:Button:create_button.html.twig',
  2368. );
  2369. }
  2370. if (in_array($action, array('show', 'delete', 'acl', 'history')) && $object) {
  2371. $list['edit'] = array(
  2372. 'template' => 'SonataAdminBundle:Button:edit_button.html.twig',
  2373. );
  2374. }
  2375. if (in_array($action, array('show', 'edit', 'acl')) && $object) {
  2376. $list['history'] = array(
  2377. 'template' => 'SonataAdminBundle:Button:history_button.html.twig',
  2378. );
  2379. }
  2380. if (in_array($action, array('edit', 'history')) && $object) {
  2381. $list['acl'] = array(
  2382. 'template' => 'SonataAdminBundle:Button:acl_button.html.twig',
  2383. );
  2384. }
  2385. if (in_array($action, array('edit', 'history', 'acl')) && $object) {
  2386. $list['show'] = array(
  2387. 'template' => 'SonataAdminBundle:Button:show_button.html.twig',
  2388. );
  2389. }
  2390. if (in_array($action, array('show', 'edit', 'delete', 'acl', 'batch'))) {
  2391. $list['list'] = array(
  2392. 'template' => 'SonataAdminBundle:Button:list_button.html.twig',
  2393. );
  2394. }
  2395. return $list;
  2396. }
  2397. /**
  2398. * @param string $action
  2399. * @param mixed $object
  2400. *
  2401. * @return array
  2402. */
  2403. public function getActionButtons($action, $object = null)
  2404. {
  2405. $list = $this->configureActionButtons($action, $object);
  2406. foreach ($this->getExtensions() as $extension) {
  2407. // TODO: remove method check in next major release
  2408. if (method_exists($extension, 'configureActionButtons')) {
  2409. $list = $extension->configureActionButtons($this, $list, $action, $object);
  2410. }
  2411. }
  2412. return $list;
  2413. }
  2414. /**
  2415. * Get the list of actions that can be accessed directly from the dashboard.
  2416. *
  2417. * @return array
  2418. */
  2419. public function getDashboardActions()
  2420. {
  2421. $actions = array();
  2422. if ($this->hasRoute('create') && $this->isGranted('CREATE')) {
  2423. $actions['create'] = array(
  2424. 'label' => 'link_add',
  2425. 'translation_domain' => 'SonataAdminBundle',
  2426. 'template' => 'SonataAdminBundle:CRUD:dashboard__action_create.html.twig',
  2427. 'url' => $this->generateUrl('create'),
  2428. 'icon' => 'plus-circle',
  2429. );
  2430. }
  2431. if ($this->hasRoute('list') && $this->isGranted('LIST')) {
  2432. $actions['list'] = array(
  2433. 'label' => 'link_list',
  2434. 'translation_domain' => 'SonataAdminBundle',
  2435. 'url' => $this->generateUrl('list'),
  2436. 'icon' => 'list',
  2437. );
  2438. }
  2439. return $actions;
  2440. }
  2441. /**
  2442. * Setting to true will enable mosaic button for the admin screen.
  2443. * Setting to false will hide mosaic button for the admin screen.
  2444. *
  2445. * @param bool $isShown
  2446. */
  2447. final public function showMosaicButton($isShown)
  2448. {
  2449. if ($isShown) {
  2450. $this->listModes['mosaic'] = array('class' => self::MOSAIC_ICON_CLASS);
  2451. } else {
  2452. unset($this->listModes['mosaic']);
  2453. }
  2454. }
  2455. /**
  2456. * @param FormMapper $form
  2457. */
  2458. final public function getSearchResultLink($object)
  2459. {
  2460. foreach ($this->searchResultActions as $action) {
  2461. if ($this->hasRoute($action) && $this->hasAccess($action, $object)) {
  2462. return $this->generateObjectUrl($action, $object);
  2463. }
  2464. }
  2465. return;
  2466. }
  2467. /**
  2468. * {@inheritdoc}
  2469. */
  2470. protected function configureFormFields(FormMapper $form)
  2471. {
  2472. }
  2473. /**
  2474. * @param ListMapper $list
  2475. */
  2476. protected function configureListFields(ListMapper $list)
  2477. {
  2478. }
  2479. /**
  2480. * @param DatagridMapper $filter
  2481. */
  2482. protected function configureDatagridFilters(DatagridMapper $filter)
  2483. {
  2484. }
  2485. /**
  2486. * @param ShowMapper $show
  2487. */
  2488. protected function configureShowFields(ShowMapper $show)
  2489. {
  2490. }
  2491. /**
  2492. * @param RouteCollection $collection
  2493. */
  2494. protected function configureRoutes(RouteCollection $collection)
  2495. {
  2496. }
  2497. /**
  2498. * Allows you to customize batch actions.
  2499. *
  2500. * @param array $actions List of actions
  2501. *
  2502. * @return array
  2503. */
  2504. protected function configureBatchActions($actions)
  2505. {
  2506. return $actions;
  2507. }
  2508. /**
  2509. * DEPRECATED: Use configureTabMenu instead.
  2510. *
  2511. * @param MenuItemInterface $menu
  2512. * @param $action
  2513. * @param AdminInterface $childAdmin
  2514. *
  2515. * @return mixed
  2516. *
  2517. * @deprecated Use configureTabMenu instead
  2518. */
  2519. protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
  2520. {
  2521. }
  2522. /**
  2523. * Configures the tab menu in your admin.
  2524. *
  2525. * @param MenuItemInterface $menu
  2526. * @param string $action
  2527. * @param AdminInterface $childAdmin
  2528. *
  2529. * @return mixed
  2530. */
  2531. protected function configureTabMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
  2532. {
  2533. // Use configureSideMenu not to mess with previous overrides
  2534. // TODO remove once deprecation period is over
  2535. $this->configureSideMenu($menu, $action, $childAdmin);
  2536. }
  2537. /**
  2538. * build the view FieldDescription array.
  2539. */
  2540. protected function buildShow()
  2541. {
  2542. if ($this->show) {
  2543. return;
  2544. }
  2545. $this->show = new FieldDescriptionCollection();
  2546. $mapper = new ShowMapper($this->showBuilder, $this->show, $this);
  2547. $this->configureShowFields($mapper);
  2548. foreach ($this->getExtensions() as $extension) {
  2549. $extension->configureShowFields($mapper);
  2550. }
  2551. }
  2552. /**
  2553. * build the list FieldDescription array.
  2554. */
  2555. protected function buildList()
  2556. {
  2557. if ($this->list) {
  2558. return;
  2559. }
  2560. $this->list = $this->getListBuilder()->getBaseList();
  2561. $mapper = new ListMapper($this->getListBuilder(), $this->list, $this);
  2562. if (count($this->getBatchActions()) > 0) {
  2563. $fieldDescription = $this->getModelManager()->getNewFieldDescriptionInstance($this->getClass(), 'batch', array(
  2564. 'label' => 'batch',
  2565. 'code' => '_batch',
  2566. 'sortable' => false,
  2567. 'virtual_field' => true,
  2568. ));
  2569. $fieldDescription->setAdmin($this);
  2570. $fieldDescription->setTemplate($this->getTemplate('batch'));
  2571. $mapper->add($fieldDescription, 'batch');
  2572. }
  2573. $this->configureListFields($mapper);
  2574. foreach ($this->getExtensions() as $extension) {
  2575. $extension->configureListFields($mapper);
  2576. }
  2577. if ($this->hasRequest() && $this->getRequest()->isXmlHttpRequest()) {
  2578. $fieldDescription = $this->getModelManager()->getNewFieldDescriptionInstance($this->getClass(), 'select', array(
  2579. 'label' => false,
  2580. 'code' => '_select',
  2581. 'sortable' => false,
  2582. 'virtual_field' => false,
  2583. ));
  2584. $fieldDescription->setAdmin($this);
  2585. $fieldDescription->setTemplate($this->getTemplate('select'));
  2586. $mapper->add($fieldDescription, 'select');
  2587. }
  2588. }
  2589. /**
  2590. * Build the form FieldDescription collection.
  2591. */
  2592. protected function buildForm()
  2593. {
  2594. if ($this->form) {
  2595. return;
  2596. }
  2597. // append parent object if any
  2598. // todo : clean the way the Admin class can retrieve set the object
  2599. if ($this->isChild() && $this->getParentAssociationMapping()) {
  2600. $parent = $this->getParent()->getObject($this->request->get($this->getParent()->getIdParameter()));
  2601. $propertyAccessor = $this->getConfigurationPool()->getPropertyAccessor();
  2602. $propertyPath = new PropertyPath($this->getParentAssociationMapping());
  2603. $object = $this->getSubject();
  2604. $value = $propertyAccessor->getValue($object, $propertyPath);
  2605. if (is_array($value) || ($value instanceof \Traversable && $value instanceof \ArrayAccess)) {
  2606. $value[] = $parent;
  2607. $propertyAccessor->setValue($object, $propertyPath, $value);
  2608. } else {
  2609. $propertyAccessor->setValue($object, $propertyPath, $parent);
  2610. }
  2611. }
  2612. $this->form = $this->getFormBuilder()->getForm();
  2613. }
  2614. /**
  2615. * Gets the subclass corresponding to the given name.
  2616. *
  2617. * @param string $name The name of the sub class
  2618. *
  2619. * @return string the subclass
  2620. */
  2621. protected function getSubClass($name)
  2622. {
  2623. if ($this->hasSubClass($name)) {
  2624. return $this->subClasses[$name];
  2625. }
  2626. throw new \RuntimeException(sprintf('Unable to find the subclass `%s` for admin `%s`', $name, get_class($this)));
  2627. }
  2628. /**
  2629. * Attach the inline validator to the model metadata, this must be done once per admin.
  2630. */
  2631. protected function attachInlineValidator()
  2632. {
  2633. $admin = $this;
  2634. // add the custom inline validation option
  2635. // TODO: Remove conditional method when bumping requirements to SF 2.5+
  2636. if (method_exists($this->validator, 'getMetadataFor')) {
  2637. $metadata = $this->validator->getMetadataFor($this->getClass());
  2638. } else {
  2639. $metadata = $this->validator->getMetadataFactory()->getMetadataFor($this->getClass());
  2640. }
  2641. $metadata->addConstraint(new InlineConstraint(array(
  2642. 'service' => $this,
  2643. 'method' => function (ErrorElement $errorElement, $object) use ($admin) {
  2644. /* @var \Sonata\AdminBundle\Admin\AdminInterface $admin */
  2645. // This avoid the main validation to be cascaded to children
  2646. // The problem occurs when a model Page has a collection of Page as property
  2647. if ($admin->hasSubject() && spl_object_hash($object) !== spl_object_hash($admin->getSubject())) {
  2648. return;
  2649. }
  2650. $admin->validate($errorElement, $object);
  2651. foreach ($admin->getExtensions() as $extension) {
  2652. $extension->validate($admin, $errorElement, $object);
  2653. }
  2654. },
  2655. 'serializingWarning' => true,
  2656. )));
  2657. }
  2658. /**
  2659. * Predefine per page options.
  2660. */
  2661. protected function predefinePerPageOptions()
  2662. {
  2663. array_unshift($this->perPageOptions, $this->maxPerPage);
  2664. $this->perPageOptions = array_unique($this->perPageOptions);
  2665. sort($this->perPageOptions);
  2666. }
  2667. /**
  2668. * Return list routes with permissions name.
  2669. *
  2670. * @return array
  2671. */
  2672. protected function getAccess()
  2673. {
  2674. $access = array_merge(array(
  2675. 'acl' => 'MASTER',
  2676. 'export' => 'EXPORT',
  2677. 'historyCompareRevisions' => 'EDIT',
  2678. 'historyViewRevision' => 'EDIT',
  2679. 'history' => 'EDIT',
  2680. 'edit' => 'EDIT',
  2681. 'show' => 'VIEW',
  2682. 'create' => 'CREATE',
  2683. 'delete' => 'DELETE',
  2684. 'batchDelete' => 'DELETE',
  2685. 'list' => 'LIST',
  2686. ), $this->getAccessMapping());
  2687. foreach ($this->extensions as $extension) {
  2688. // TODO: remove method check in next major release
  2689. if (method_exists($extension, 'getAccessMapping')) {
  2690. $access = array_merge($access, $extension->getAccessMapping($this));
  2691. }
  2692. }
  2693. return $access;
  2694. }
  2695. /**
  2696. * Build all the related urls to the current admin.
  2697. */
  2698. private function buildRoutes()
  2699. {
  2700. if ($this->loaded['routes']) {
  2701. return;
  2702. }
  2703. $this->loaded['routes'] = true;
  2704. $this->routes = new RouteCollection(
  2705. $this->getBaseCodeRoute(),
  2706. $this->getBaseRouteName(),
  2707. $this->getBaseRoutePattern(),
  2708. $this->getBaseControllerName()
  2709. );
  2710. $this->routeBuilder->build($this, $this->routes);
  2711. $this->configureRoutes($this->routes);
  2712. foreach ($this->getExtensions() as $extension) {
  2713. $extension->configureRoutes($this, $this->routes);
  2714. }
  2715. }
  2716. }