CRUDController.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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\Controller;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\NullLogger;
  13. use Sonata\AdminBundle\Admin\AdminInterface;
  14. use Sonata\AdminBundle\Admin\BaseFieldDescription;
  15. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  16. use Sonata\AdminBundle\Exception\LockException;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. use Sonata\AdminBundle\Util\AdminObjectAclData;
  19. use Sonata\AdminBundle\Util\AdminObjectAclManipulator;
  20. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  21. use Symfony\Component\DependencyInjection\ContainerInterface;
  22. use Symfony\Component\Form\Form;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\RedirectResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpKernel\Exception\HttpException;
  28. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  29. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  30. use Symfony\Component\Security\Csrf\CsrfToken;
  31. /**
  32. * Class CRUDController.
  33. *
  34. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  35. */
  36. class CRUDController extends Controller
  37. {
  38. /**
  39. * The related Admin class.
  40. *
  41. * @var AdminInterface
  42. */
  43. protected $admin;
  44. /**
  45. * Render JSON.
  46. *
  47. * @param mixed $data
  48. * @param int $status
  49. * @param array $headers
  50. * @param Request $request
  51. *
  52. * @return Response with json encoded data
  53. */
  54. protected function renderJson($data, $status = 200, $headers = array(), Request $request = null)
  55. {
  56. return new JsonResponse($data, $status, $headers);
  57. }
  58. /**
  59. * Returns true if the request is a XMLHttpRequest.
  60. *
  61. * @param Request $request
  62. *
  63. * @return bool True if the request is an XMLHttpRequest, false otherwise
  64. */
  65. protected function isXmlHttpRequest(Request $request = null)
  66. {
  67. $request = $this->resolveRequest($request);
  68. return $request->isXmlHttpRequest() || $request->get('_xml_http_request');
  69. }
  70. /**
  71. * Returns the correct RESTful verb, given either by the request itself or
  72. * via the "_method" parameter.
  73. *
  74. * @param Request $request
  75. *
  76. * @return string HTTP method, either
  77. */
  78. protected function getRestMethod(Request $request = null)
  79. {
  80. $request = $this->resolveRequest($request);
  81. if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) {
  82. return $request->getMethod();
  83. }
  84. return $request->request->get('_method');
  85. }
  86. /**
  87. * Sets the Container associated with this Controller.
  88. *
  89. * @param ContainerInterface $container A ContainerInterface instance
  90. */
  91. public function setContainer(ContainerInterface $container = null)
  92. {
  93. $this->container = $container;
  94. $this->configure();
  95. }
  96. /**
  97. * Contextualize the admin class depends on the current request.
  98. *
  99. * @throws \RuntimeException
  100. */
  101. protected function configure()
  102. {
  103. $request = $this->getRequest();
  104. $adminCode = $request->get('_sonata_admin');
  105. if (!$adminCode) {
  106. throw new \RuntimeException(sprintf(
  107. 'There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`',
  108. get_class($this),
  109. $request->get('_route')
  110. ));
  111. }
  112. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  113. if (!$this->admin) {
  114. throw new \RuntimeException(sprintf(
  115. 'Unable to find the admin class related to the current controller (%s)',
  116. get_class($this)
  117. ));
  118. }
  119. $rootAdmin = $this->admin;
  120. if ($this->admin->isChild()) {
  121. $this->admin->setCurrentChild(true);
  122. $rootAdmin = $rootAdmin->getParent();
  123. }
  124. $rootAdmin->setRequest($request);
  125. if ($request->get('uniqid')) {
  126. $this->admin->setUniqid($request->get('uniqid'));
  127. }
  128. }
  129. /**
  130. * Proxy for the logger service of the container.
  131. * If no such service is found, a NullLogger is returned.
  132. *
  133. * @return LoggerInterface
  134. */
  135. protected function getLogger()
  136. {
  137. if ($this->container->has('logger')) {
  138. return $this->container->get('logger');
  139. } else {
  140. return new NullLogger();
  141. }
  142. }
  143. /**
  144. * Returns the base template name.
  145. *
  146. * @param Request $request
  147. *
  148. * @return string The template name
  149. */
  150. protected function getBaseTemplate(Request $request = null)
  151. {
  152. $request = $this->resolveRequest($request);
  153. if ($this->isXmlHttpRequest($request)) {
  154. return $this->admin->getTemplate('ajax');
  155. }
  156. return $this->admin->getTemplate('layout');
  157. }
  158. /**
  159. * {@inheritdoc}
  160. *
  161. * @param Request $request
  162. */
  163. public function render($view, array $parameters = array(), Response $response = null, Request $request = null)
  164. {
  165. $request = $this->resolveRequest($request);
  166. $parameters['admin'] = isset($parameters['admin']) ?
  167. $parameters['admin'] :
  168. $this->admin;
  169. $parameters['base_template'] = isset($parameters['base_template']) ?
  170. $parameters['base_template'] :
  171. $this->getBaseTemplate($request);
  172. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  173. return parent::render($view, $parameters, $response);
  174. }
  175. /**
  176. * @param \Exception $e
  177. *
  178. * @throws \Exception
  179. */
  180. protected function handleModelManagerException(\Exception $e)
  181. {
  182. if ($this->get('kernel')->isDebug()) {
  183. throw $e;
  184. }
  185. $context = array('exception' => $e);
  186. if ($e->getPrevious()) {
  187. $context['previous_exception_message'] = $e->getPrevious()->getMessage();
  188. }
  189. $this->getLogger()->error($e->getMessage(), $context);
  190. }
  191. /**
  192. * List action.
  193. *
  194. * @param Request $request
  195. *
  196. * @return Response
  197. *
  198. * @throws AccessDeniedException If access is not granted
  199. */
  200. public function listAction(Request $request = null)
  201. {
  202. $request = $this->resolveRequest($request);
  203. $this->admin->checkAccess('list');
  204. $preResponse = $this->preList($request);
  205. if ($preResponse !== null) {
  206. return $preResponse;
  207. }
  208. if ($listMode = $request->get('_list_mode')) {
  209. $this->admin->setListMode($listMode);
  210. }
  211. $datagrid = $this->admin->getDatagrid();
  212. $formView = $datagrid->getForm()->createView();
  213. // set the theme for the current Admin Form
  214. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  215. return $this->render($this->admin->getTemplate('list'), array(
  216. 'action' => 'list',
  217. 'form' => $formView,
  218. 'datagrid' => $datagrid,
  219. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  220. ), null, $request);
  221. }
  222. /**
  223. * Execute a batch delete.
  224. *
  225. * @param ProxyQueryInterface $query
  226. * @param Request $request
  227. *
  228. * @return RedirectResponse
  229. *
  230. * @throws AccessDeniedException If access is not granted
  231. */
  232. public function batchActionDelete(ProxyQueryInterface $query, Request $request = null)
  233. {
  234. $this->admin->checkAccess('batchDelete');
  235. $request = $this->resolveRequest($request);
  236. $modelManager = $this->admin->getModelManager();
  237. try {
  238. $modelManager->batchDelete($this->admin->getClass(), $query);
  239. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  240. } catch (ModelManagerException $e) {
  241. $this->handleModelManagerException($e);
  242. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  243. }
  244. return new RedirectResponse($this->admin->generateUrl(
  245. 'list',
  246. array('filter' => $this->admin->getFilterParameters())
  247. ));
  248. }
  249. /**
  250. * Delete action.
  251. *
  252. * @param int|string|null $id
  253. * @param Request $request
  254. *
  255. * @return Response|RedirectResponse
  256. *
  257. * @throws NotFoundHttpException If the object does not exist
  258. * @throws AccessDeniedException If access is not granted
  259. */
  260. public function deleteAction($id, Request $request = null)
  261. {
  262. $request = $this->resolveRequest($request);
  263. $id = $request->get($this->admin->getIdParameter());
  264. $object = $this->admin->getObject($id);
  265. if (!$object) {
  266. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  267. }
  268. $this->admin->checkAccess('delete', $object);
  269. $preResponse = $this->preDelete($request, $object);
  270. if ($preResponse !== null) {
  271. return $preResponse;
  272. }
  273. if ($this->getRestMethod($request) === 'DELETE') {
  274. // check the csrf token
  275. $this->validateCsrfToken('sonata.delete', $request);
  276. $objectName = $this->admin->toString($object);
  277. try {
  278. $this->admin->delete($object);
  279. if ($this->isXmlHttpRequest($request)) {
  280. return $this->renderJson(array('result' => 'ok'), 200, array(), $request);
  281. }
  282. $this->addFlash(
  283. 'sonata_flash_success',
  284. $this->admin->trans(
  285. 'flash_delete_success',
  286. array('%name%' => $this->escapeHtml($objectName)),
  287. 'SonataAdminBundle'
  288. )
  289. );
  290. } catch (ModelManagerException $e) {
  291. $this->handleModelManagerException($e);
  292. if ($this->isXmlHttpRequest($request)) {
  293. return $this->renderJson(array('result' => 'error'), 200, array(), $request);
  294. }
  295. $this->addFlash(
  296. 'sonata_flash_error',
  297. $this->admin->trans(
  298. 'flash_delete_error',
  299. array('%name%' => $this->escapeHtml($objectName)),
  300. 'SonataAdminBundle'
  301. )
  302. );
  303. }
  304. return $this->redirectTo($object, $request);
  305. }
  306. return $this->render($this->admin->getTemplate('delete'), array(
  307. 'object' => $object,
  308. 'action' => 'delete',
  309. 'csrf_token' => $this->getCsrfToken('sonata.delete'),
  310. ), null, $request);
  311. }
  312. /**
  313. * Edit action.
  314. *
  315. * @param int|string|null $id
  316. * @param Request $request
  317. *
  318. * @return Response|RedirectResponse
  319. *
  320. * @throws NotFoundHttpException If the object does not exist
  321. * @throws AccessDeniedException If access is not granted
  322. */
  323. public function editAction($id = null, Request $request = null)
  324. {
  325. $request = $this->resolveRequest($request);
  326. // the key used to lookup the template
  327. $templateKey = 'edit';
  328. $id = $request->get($this->admin->getIdParameter());
  329. $object = $this->admin->getObject($id);
  330. if (!$object) {
  331. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  332. }
  333. $this->admin->checkAccess('edit', $object);
  334. $preResponse = $this->preEdit($request, $object);
  335. if ($preResponse !== null) {
  336. return $preResponse;
  337. }
  338. $this->admin->setSubject($object);
  339. /** @var $form Form */
  340. $form = $this->admin->getForm();
  341. $form->setData($object);
  342. $form->handleRequest($request);
  343. if ($form->isSubmitted()) {
  344. //TODO: remove this check for 3.0
  345. if (method_exists($this->admin, 'preValidate')) {
  346. $this->admin->preValidate($object);
  347. }
  348. $isFormValid = $form->isValid();
  349. // persist if the form was valid and if in preview mode the preview was approved
  350. if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  351. try {
  352. $object = $this->admin->update($object);
  353. if ($this->isXmlHttpRequest($request)) {
  354. return $this->renderJson(array(
  355. 'result' => 'ok',
  356. 'objectId' => $this->admin->getNormalizedIdentifier($object),
  357. 'objectName' => $this->escapeHtml($this->admin->toString($object)),
  358. ), 200, array(), $request);
  359. }
  360. $this->addFlash(
  361. 'sonata_flash_success',
  362. $this->admin->trans(
  363. 'flash_edit_success',
  364. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  365. 'SonataAdminBundle'
  366. )
  367. );
  368. // redirect to edit mode
  369. return $this->redirectTo($object, $request);
  370. } catch (ModelManagerException $e) {
  371. $this->handleModelManagerException($e);
  372. $isFormValid = false;
  373. } catch (LockException $e) {
  374. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_lock_error', array(
  375. '%name%' => $this->escapeHtml($this->admin->toString($object)),
  376. '%link_start%' => '<a href="'.$this->admin->generateObjectUrl('edit', $object).'">',
  377. '%link_end%' => '</a>',
  378. ), 'SonataAdminBundle'));
  379. }
  380. }
  381. // show an error message if the form failed validation
  382. if (!$isFormValid) {
  383. if (!$this->isXmlHttpRequest($request)) {
  384. $this->addFlash(
  385. 'sonata_flash_error',
  386. $this->admin->trans(
  387. 'flash_edit_error',
  388. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  389. 'SonataAdminBundle'
  390. )
  391. );
  392. }
  393. } elseif ($this->isPreviewRequested($request)) {
  394. // enable the preview template if the form was valid and preview was requested
  395. $templateKey = 'preview';
  396. $this->admin->getShow();
  397. }
  398. }
  399. $view = $form->createView();
  400. // set the theme for the current Admin Form
  401. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  402. return $this->render($this->admin->getTemplate($templateKey), array(
  403. 'action' => 'edit',
  404. 'form' => $view,
  405. 'object' => $object,
  406. ), null, $request);
  407. }
  408. /**
  409. * Redirect the user depend on this choice.
  410. *
  411. * @param object $object
  412. * @param Request $request
  413. *
  414. * @return RedirectResponse
  415. */
  416. protected function redirectTo($object, Request $request = null)
  417. {
  418. $request = $this->resolveRequest($request);
  419. $url = false;
  420. if (null !== $request->get('btn_update_and_list')) {
  421. $url = $this->admin->generateUrl('list');
  422. }
  423. if (null !== $request->get('btn_create_and_list')) {
  424. $url = $this->admin->generateUrl('list');
  425. }
  426. if (null !== $request->get('btn_create_and_create')) {
  427. $params = array();
  428. if ($this->admin->hasActiveSubClass()) {
  429. $params['subclass'] = $request->get('subclass');
  430. }
  431. $url = $this->admin->generateUrl('create', $params);
  432. }
  433. if ($this->getRestMethod($request) === 'DELETE') {
  434. $url = $this->admin->generateUrl('list');
  435. }
  436. if (!$url) {
  437. foreach (array('edit', 'show') as $route) {
  438. if ($this->admin->hasRoute($route) && $this->admin->isGranted(strtoupper($route), $object)) {
  439. $url = $this->admin->generateObjectUrl($route, $object);
  440. break;
  441. }
  442. }
  443. }
  444. if (!$url) {
  445. $url = $this->admin->generateUrl('list');
  446. }
  447. return new RedirectResponse($url);
  448. }
  449. /**
  450. * Batch action.
  451. *
  452. * @param Request $request
  453. *
  454. * @return Response|RedirectResponse
  455. *
  456. * @throws NotFoundHttpException If the HTTP method is not POST
  457. * @throws \RuntimeException If the batch action is not defined
  458. */
  459. public function batchAction(Request $request = null)
  460. {
  461. $request = $this->resolveRequest($request);
  462. $restMethod = $this->getRestMethod($request);
  463. if ('POST' !== $restMethod) {
  464. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  465. }
  466. // check the csrf token
  467. $this->validateCsrfToken('sonata.batch', $request);
  468. $confirmation = $request->get('confirmation', false);
  469. if ($data = json_decode($request->get('data'), true)) {
  470. $action = $data['action'];
  471. $idx = $data['idx'];
  472. $allElements = $data['all_elements'];
  473. $request->request->replace(array_merge($request->request->all(), $data));
  474. } else {
  475. $request->request->set('idx', $request->get('idx', array()));
  476. $request->request->set('all_elements', $request->get('all_elements', false));
  477. $action = $request->get('action');
  478. $idx = $request->get('idx');
  479. $allElements = $request->get('all_elements');
  480. $data = $request->request->all();
  481. unset($data['_sonata_csrf_token']);
  482. }
  483. $batchActions = $this->admin->getBatchActions();
  484. if (!array_key_exists($action, $batchActions)) {
  485. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  486. }
  487. $camelizedAction = BaseFieldDescription::camelize($action);
  488. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  489. if (method_exists($this, $isRelevantAction)) {
  490. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements, $request);
  491. } else {
  492. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  493. }
  494. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  495. $nonRelevantMessage = 'flash_batch_empty';
  496. }
  497. $datagrid = $this->admin->getDatagrid();
  498. $datagrid->buildPager();
  499. if (true !== $nonRelevantMessage) {
  500. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  501. return new RedirectResponse(
  502. $this->admin->generateUrl(
  503. 'list',
  504. array('filter' => $this->admin->getFilterParameters())
  505. )
  506. );
  507. }
  508. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ?
  509. $batchActions[$action]['ask_confirmation'] :
  510. true;
  511. if ($askConfirmation && $confirmation != 'ok') {
  512. $translationDomain = $batchActions[$action]['translation_domain'] ?: $this->admin->getTranslationDomain();
  513. $actionLabel = $this->admin->trans($batchActions[$action]['label'], array(), $translationDomain);
  514. $formView = $datagrid->getForm()->createView();
  515. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  516. 'action' => 'list',
  517. 'action_label' => $actionLabel,
  518. 'datagrid' => $datagrid,
  519. 'form' => $formView,
  520. 'data' => $data,
  521. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  522. ), null, $request);
  523. }
  524. // execute the action, batchActionXxxxx
  525. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  526. if (!is_callable(array($this, $finalAction))) {
  527. throw new \RuntimeException(sprintf('A `%s::%s` method must be callable', get_class($this), $finalAction));
  528. }
  529. $query = $datagrid->getQuery();
  530. $query->setFirstResult(null);
  531. $query->setMaxResults(null);
  532. $this->admin->preBatchAction($action, $query, $idx, $allElements);
  533. if (count($idx) > 0) {
  534. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  535. } elseif (!$allElements) {
  536. $query = null;
  537. }
  538. return call_user_func(array($this, $finalAction), $query, $request);
  539. }
  540. /**
  541. * Create action.
  542. *
  543. * @param Request $request
  544. *
  545. * @return Response
  546. *
  547. * @throws AccessDeniedException If access is not granted
  548. */
  549. public function createAction(Request $request = null)
  550. {
  551. $request = $this->resolveRequest($request);
  552. // the key used to lookup the template
  553. $templateKey = 'edit';
  554. $this->admin->checkAccess('create');
  555. $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  556. if ($class->isAbstract()) {
  557. return $this->render(
  558. 'SonataAdminBundle:CRUD:select_subclass.html.twig',
  559. array(
  560. 'base_template' => $this->getBaseTemplate(),
  561. 'admin' => $this->admin,
  562. 'action' => 'create',
  563. ),
  564. null,
  565. $request
  566. );
  567. }
  568. $object = $this->admin->getNewInstance();
  569. $preResponse = $this->preCreate($request, $object);
  570. if ($preResponse !== null) {
  571. return $preResponse;
  572. }
  573. $this->admin->setSubject($object);
  574. /** @var $form \Symfony\Component\Form\Form */
  575. $form = $this->admin->getForm();
  576. $form->setData($object);
  577. $form->handleRequest($request);
  578. if ($form->isSubmitted()) {
  579. //TODO: remove this check for 3.0
  580. if (method_exists($this->admin, 'preValidate')) {
  581. $this->admin->preValidate($object);
  582. }
  583. $isFormValid = $form->isValid();
  584. // persist if the form was valid and if in preview mode the preview was approved
  585. if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  586. $this->admin->checkAccess('create', $object);
  587. try {
  588. $object = $this->admin->create($object);
  589. if ($this->isXmlHttpRequest($request)) {
  590. return $this->renderJson(array(
  591. 'result' => 'ok',
  592. 'objectId' => $this->admin->getNormalizedIdentifier($object),
  593. ), 200, array(), $request);
  594. }
  595. $this->addFlash(
  596. 'sonata_flash_success',
  597. $this->admin->trans(
  598. 'flash_create_success',
  599. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  600. 'SonataAdminBundle'
  601. )
  602. );
  603. // redirect to edit mode
  604. return $this->redirectTo($object, $request);
  605. } catch (ModelManagerException $e) {
  606. $this->handleModelManagerException($e);
  607. $isFormValid = false;
  608. }
  609. }
  610. // show an error message if the form failed validation
  611. if (!$isFormValid) {
  612. if (!$this->isXmlHttpRequest($request)) {
  613. $this->addFlash(
  614. 'sonata_flash_error',
  615. $this->admin->trans(
  616. 'flash_create_error',
  617. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  618. 'SonataAdminBundle'
  619. )
  620. );
  621. }
  622. } elseif ($this->isPreviewRequested($request)) {
  623. // pick the preview template if the form was valid and preview was requested
  624. $templateKey = 'preview';
  625. $this->admin->getShow();
  626. }
  627. }
  628. $view = $form->createView();
  629. // set the theme for the current Admin Form
  630. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  631. return $this->render($this->admin->getTemplate($templateKey), array(
  632. 'action' => 'create',
  633. 'form' => $view,
  634. 'object' => $object,
  635. ), null, $request);
  636. }
  637. /**
  638. * Returns true if the preview is requested to be shown.
  639. *
  640. * @param Request $request
  641. *
  642. * @return bool
  643. */
  644. protected function isPreviewRequested(Request $request = null)
  645. {
  646. $request = $this->resolveRequest($request);
  647. return $request->get('btn_preview') !== null;
  648. }
  649. /**
  650. * Returns true if the preview has been approved.
  651. *
  652. * @param Request $request
  653. *
  654. * @return bool
  655. */
  656. protected function isPreviewApproved(Request $request = null)
  657. {
  658. $request = $this->resolveRequest($request);
  659. return $request->get('btn_preview_approve') !== null;
  660. }
  661. /**
  662. * Returns true if the request is in the preview workflow.
  663. *
  664. * That means either a preview is requested or the preview has already been shown
  665. * and it got approved/declined.
  666. *
  667. * @param Request $request
  668. *
  669. * @return bool
  670. */
  671. protected function isInPreviewMode(Request $request = null)
  672. {
  673. $request = $this->resolveRequest($request);
  674. return $this->admin->supportsPreviewMode()
  675. && ($this->isPreviewRequested($request)
  676. || $this->isPreviewApproved($request)
  677. || $this->isPreviewDeclined($request));
  678. }
  679. /**
  680. * Returns true if the preview has been declined.
  681. *
  682. * @param Request $request
  683. *
  684. * @return bool
  685. */
  686. protected function isPreviewDeclined(Request $request = null)
  687. {
  688. $request = $this->resolveRequest($request);
  689. return $request->get('btn_preview_decline') !== null;
  690. }
  691. /**
  692. * Show action.
  693. *
  694. * @param int|string|null $id
  695. * @param Request $request
  696. *
  697. * @return Response
  698. *
  699. * @throws NotFoundHttpException If the object does not exist
  700. * @throws AccessDeniedException If access is not granted
  701. */
  702. public function showAction($id = null, Request $request = null)
  703. {
  704. $request = $this->resolveRequest($request);
  705. $id = $request->get($this->admin->getIdParameter());
  706. $object = $this->admin->getObject($id);
  707. if (!$object) {
  708. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  709. }
  710. $this->admin->checkAccess('show', $object);
  711. $preResponse = $this->preShow($request, $object);
  712. if ($preResponse !== null) {
  713. return $preResponse;
  714. }
  715. $this->admin->setSubject($object);
  716. return $this->render($this->admin->getTemplate('show'), array(
  717. 'action' => 'show',
  718. 'object' => $object,
  719. 'elements' => $this->admin->getShow(),
  720. ), null, $request);
  721. }
  722. /**
  723. * Show history revisions for object.
  724. *
  725. * @param int|string|null $id
  726. * @param Request $request
  727. *
  728. * @return Response
  729. *
  730. * @throws AccessDeniedException If access is not granted
  731. * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  732. */
  733. public function historyAction($id = null, Request $request = null)
  734. {
  735. $request = $this->resolveRequest($request);
  736. $id = $request->get($this->admin->getIdParameter());
  737. $object = $this->admin->getObject($id);
  738. if (!$object) {
  739. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  740. }
  741. $this->admin->checkAccess('history', $object);
  742. $manager = $this->get('sonata.admin.audit.manager');
  743. if (!$manager->hasReader($this->admin->getClass())) {
  744. throw $this->createNotFoundException(
  745. sprintf(
  746. 'unable to find the audit reader for class : %s',
  747. $this->admin->getClass()
  748. )
  749. );
  750. }
  751. $reader = $manager->getReader($this->admin->getClass());
  752. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  753. return $this->render($this->admin->getTemplate('history'), array(
  754. 'action' => 'history',
  755. 'object' => $object,
  756. 'revisions' => $revisions,
  757. 'currentRevision' => $revisions ? current($revisions) : false,
  758. ), null, $request);
  759. }
  760. /**
  761. * View history revision of object.
  762. *
  763. * @param int|string|null $id
  764. * @param string|null $revision
  765. * @param Request $request
  766. *
  767. * @return Response
  768. *
  769. * @throws AccessDeniedException If access is not granted
  770. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  771. */
  772. public function historyViewRevisionAction($id = null, $revision = null, Request $request = null)
  773. {
  774. $request = $this->resolveRequest($request);
  775. $id = $request->get($this->admin->getIdParameter());
  776. $object = $this->admin->getObject($id);
  777. if (!$object) {
  778. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  779. }
  780. $this->admin->checkAccess('historyViewRevision', $object);
  781. $manager = $this->get('sonata.admin.audit.manager');
  782. if (!$manager->hasReader($this->admin->getClass())) {
  783. throw $this->createNotFoundException(
  784. sprintf(
  785. 'unable to find the audit reader for class : %s',
  786. $this->admin->getClass()
  787. )
  788. );
  789. }
  790. $reader = $manager->getReader($this->admin->getClass());
  791. // retrieve the revisioned object
  792. $object = $reader->find($this->admin->getClass(), $id, $revision);
  793. if (!$object) {
  794. throw $this->createNotFoundException(
  795. sprintf(
  796. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  797. $id,
  798. $revision,
  799. $this->admin->getClass()
  800. )
  801. );
  802. }
  803. $this->admin->setSubject($object);
  804. return $this->render($this->admin->getTemplate('show'), array(
  805. 'action' => 'show',
  806. 'object' => $object,
  807. 'elements' => $this->admin->getShow(),
  808. ), null, $request);
  809. }
  810. /**
  811. * Compare history revisions of object.
  812. *
  813. * @param int|string|null $id
  814. * @param int|string|null $base_revision
  815. * @param int|string|null $compare_revision
  816. * @param Request $request
  817. *
  818. * @return Response
  819. *
  820. * @throws AccessDeniedException If access is not granted
  821. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  822. */
  823. public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null, Request $request = null)
  824. {
  825. $request = $this->resolveRequest($request);
  826. $this->admin->checkAccess('historyCompareRevisions');
  827. $id = $request->get($this->admin->getIdParameter());
  828. $object = $this->admin->getObject($id);
  829. if (!$object) {
  830. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  831. }
  832. $manager = $this->get('sonata.admin.audit.manager');
  833. if (!$manager->hasReader($this->admin->getClass())) {
  834. throw $this->createNotFoundException(
  835. sprintf(
  836. 'unable to find the audit reader for class : %s',
  837. $this->admin->getClass()
  838. )
  839. );
  840. }
  841. $reader = $manager->getReader($this->admin->getClass());
  842. // retrieve the base revision
  843. $base_object = $reader->find($this->admin->getClass(), $id, $base_revision);
  844. if (!$base_object) {
  845. throw $this->createNotFoundException(
  846. sprintf(
  847. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  848. $id,
  849. $base_revision,
  850. $this->admin->getClass()
  851. )
  852. );
  853. }
  854. // retrieve the compare revision
  855. $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision);
  856. if (!$compare_object) {
  857. throw $this->createNotFoundException(
  858. sprintf(
  859. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  860. $id,
  861. $compare_revision,
  862. $this->admin->getClass()
  863. )
  864. );
  865. }
  866. $this->admin->setSubject($base_object);
  867. return $this->render($this->admin->getTemplate('show_compare'), array(
  868. 'action' => 'show',
  869. 'object' => $base_object,
  870. 'object_compare' => $compare_object,
  871. 'elements' => $this->admin->getShow(),
  872. ), null, $request);
  873. }
  874. /**
  875. * Export data to specified format.
  876. *
  877. * @param Request $request
  878. *
  879. * @return Response
  880. *
  881. * @throws AccessDeniedException If access is not granted
  882. * @throws \RuntimeException If the export format is invalid
  883. */
  884. public function exportAction(Request $request = null)
  885. {
  886. $request = $this->resolveRequest($request);
  887. $this->admin->checkAccess('export');
  888. $format = $request->get('format');
  889. $allowedExportFormats = (array) $this->admin->getExportFormats();
  890. if (!in_array($format, $allowedExportFormats)) {
  891. throw new \RuntimeException(
  892. sprintf(
  893. 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
  894. $format,
  895. $this->admin->getClass(),
  896. implode(', ', $allowedExportFormats)
  897. )
  898. );
  899. }
  900. $filename = sprintf(
  901. 'export_%s_%s.%s',
  902. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  903. date('Y_m_d_H_i_s', strtotime('now')),
  904. $format
  905. );
  906. return $this->get('sonata.admin.exporter')->getResponse(
  907. $format,
  908. $filename,
  909. $this->admin->getDataSourceIterator()
  910. );
  911. }
  912. /**
  913. * Gets ACL users.
  914. *
  915. * @return \Traversable
  916. */
  917. protected function getAclUsers()
  918. {
  919. $aclUsers = array();
  920. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  921. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  922. $userManager = $this->get($userManagerServiceName);
  923. if (method_exists($userManager, 'findUsers')) {
  924. $aclUsers = $userManager->findUsers();
  925. }
  926. }
  927. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  928. }
  929. /**
  930. * Gets ACL roles.
  931. *
  932. * @return \Traversable
  933. */
  934. protected function getAclRoles()
  935. {
  936. $aclRoles = array();
  937. $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
  938. $pool = $this->container->get('sonata.admin.pool');
  939. foreach ($pool->getAdminServiceIds() as $id) {
  940. try {
  941. $admin = $pool->getInstance($id);
  942. } catch (\Exception $e) {
  943. continue;
  944. }
  945. $baseRole = $admin->getSecurityHandler()->getBaseRole($admin);
  946. foreach ($admin->getSecurityInformation() as $role => $permissions) {
  947. $role = sprintf($baseRole, $role);
  948. $aclRoles[] = $role;
  949. }
  950. }
  951. foreach ($roleHierarchy as $name => $roles) {
  952. $aclRoles[] = $name;
  953. $aclRoles = array_merge($aclRoles, $roles);
  954. }
  955. $aclRoles = array_unique($aclRoles);
  956. return is_array($aclRoles) ? new \ArrayIterator($aclRoles) : $aclRoles;
  957. }
  958. /**
  959. * Returns the Response object associated to the acl action.
  960. *
  961. * @param int|string|null $id
  962. * @param Request $request
  963. *
  964. * @return Response|RedirectResponse
  965. *
  966. * @throws AccessDeniedException If access is not granted.
  967. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  968. */
  969. public function aclAction($id = null, Request $request = null)
  970. {
  971. $request = $this->resolveRequest($request);
  972. if (!$this->admin->isAclEnabled()) {
  973. throw $this->createNotFoundException('ACL are not enabled for this admin');
  974. }
  975. $id = $request->get($this->admin->getIdParameter());
  976. $object = $this->admin->getObject($id);
  977. if (!$object) {
  978. throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
  979. }
  980. $this->admin->checkAccess('acl', $object);
  981. $this->admin->setSubject($object);
  982. $aclUsers = $this->getAclUsers();
  983. $aclRoles = $this->getAclRoles();
  984. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  985. $adminObjectAclData = new AdminObjectAclData(
  986. $this->admin,
  987. $object,
  988. $aclUsers,
  989. $adminObjectAclManipulator->getMaskBuilderClass(),
  990. $aclRoles
  991. );
  992. $aclUsersForm = $adminObjectAclManipulator->createAclUsersForm($adminObjectAclData);
  993. $aclRolesForm = $adminObjectAclManipulator->createAclRolesForm($adminObjectAclData);
  994. if ($request->getMethod() === 'POST') {
  995. if ($request->request->has(AdminObjectAclManipulator::ACL_USERS_FORM_NAME)) {
  996. $form = $aclUsersForm;
  997. $updateMethod = 'updateAclUsers';
  998. } elseif ($request->request->has(AdminObjectAclManipulator::ACL_ROLES_FORM_NAME)) {
  999. $form = $aclRolesForm;
  1000. $updateMethod = 'updateAclRoles';
  1001. }
  1002. if (isset($form)) {
  1003. $form->handleRequest($request);
  1004. if ($form->isValid()) {
  1005. $adminObjectAclManipulator->$updateMethod($adminObjectAclData);
  1006. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  1007. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  1008. }
  1009. }
  1010. }
  1011. return $this->render($this->admin->getTemplate('acl'), array(
  1012. 'action' => 'acl',
  1013. 'permissions' => $adminObjectAclData->getUserPermissions(),
  1014. 'object' => $object,
  1015. 'users' => $aclUsers,
  1016. 'roles' => $aclRoles,
  1017. 'aclUsersForm' => $aclUsersForm->createView(),
  1018. 'aclRolesForm' => $aclRolesForm->createView(),
  1019. ), null, $request);
  1020. }
  1021. /**
  1022. * Adds a flash message for type.
  1023. *
  1024. * @param string $type
  1025. * @param string $message
  1026. *
  1027. * @TODO Remove this method when bumping requirements to Symfony >= 2.6
  1028. */
  1029. protected function addFlash($type, $message)
  1030. {
  1031. if (method_exists('Symfony\Bundle\FrameworkBundle\Controller\Controller', 'addFlash')) {
  1032. parent::addFlash($type, $message);
  1033. } else {
  1034. $this->get('session')
  1035. ->getFlashBag()
  1036. ->add($type, $message);
  1037. }
  1038. }
  1039. /**
  1040. * Validate CSRF token for action without form.
  1041. *
  1042. * @param string $intention
  1043. * @param Request $request
  1044. *
  1045. * @throws HttpException
  1046. */
  1047. protected function validateCsrfToken($intention, Request $request = null)
  1048. {
  1049. $request = $this->resolveRequest($request);
  1050. $token = $request->request->get('_sonata_csrf_token', false);
  1051. if ($this->container->has('security.csrf.token_manager')) { // SF3.0
  1052. $valid = $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($intention, $token));
  1053. } elseif ($this->container->has('form.csrf_provider')) { // < SF3.0
  1054. $valid = $this->container->get('form.csrf_provider')->isCsrfTokenValid($intention, $token);
  1055. } else {
  1056. return;
  1057. }
  1058. if (!$valid) {
  1059. throw new HttpException(400, 'The csrf token is not valid, CSRF attack?');
  1060. }
  1061. }
  1062. /**
  1063. * Escape string for html output.
  1064. *
  1065. * @param string $s
  1066. *
  1067. * @return string
  1068. */
  1069. protected function escapeHtml($s)
  1070. {
  1071. return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  1072. }
  1073. /**
  1074. * Get CSRF token.
  1075. *
  1076. * @param string $intention
  1077. *
  1078. * @return string|false
  1079. */
  1080. protected function getCsrfToken($intention)
  1081. {
  1082. if ($this->container->has('security.csrf.token_manager')) {
  1083. return $this->container->get('security.csrf.token_manager')->getToken($intention)->getValue();
  1084. }
  1085. // TODO: Remove it when bumping requirements to SF 2.4+
  1086. if ($this->container->has('form.csrf_provider')) {
  1087. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  1088. }
  1089. return false;
  1090. }
  1091. /**
  1092. * This method can be overloaded in your custom CRUD controller.
  1093. * It's called from createAction.
  1094. *
  1095. * @param Request $request
  1096. * @param mixed $object
  1097. *
  1098. * @return Response|null
  1099. */
  1100. protected function preCreate(Request $request, $object)
  1101. {
  1102. }
  1103. /**
  1104. * This method can be overloaded in your custom CRUD controller.
  1105. * It's called from editAction.
  1106. *
  1107. * @param Request $request
  1108. * @param mixed $object
  1109. *
  1110. * @return Response|null
  1111. */
  1112. protected function preEdit(Request $request, $object)
  1113. {
  1114. }
  1115. /**
  1116. * This method can be overloaded in your custom CRUD controller.
  1117. * It's called from deleteAction.
  1118. *
  1119. * @param Request $request
  1120. * @param mixed $object
  1121. *
  1122. * @return Response|null
  1123. */
  1124. protected function preDelete(Request $request, $object)
  1125. {
  1126. }
  1127. /**
  1128. * This method can be overloaded in your custom CRUD controller.
  1129. * It's called from showAction.
  1130. *
  1131. * @param Request $request
  1132. * @param mixed $object
  1133. *
  1134. * @return Response|null
  1135. */
  1136. protected function preShow(Request $request, $object)
  1137. {
  1138. }
  1139. /**
  1140. * This method can be overloaded in your custom CRUD controller.
  1141. * It's called from listAction.
  1142. *
  1143. * @param Request $request
  1144. *
  1145. * @return Response|null
  1146. */
  1147. protected function preList(Request $request)
  1148. {
  1149. }
  1150. /**
  1151. * To keep backwards compatibility with older Sonata Admin code.
  1152. *
  1153. * @internal
  1154. */
  1155. private function resolveRequest(Request $request = null)
  1156. {
  1157. if (null === $request) {
  1158. return $this->getRequest();
  1159. }
  1160. return $request;
  1161. }
  1162. /**
  1163. * @return Request
  1164. */
  1165. public function getRequest()
  1166. {
  1167. if ($this->container->has('request_stack')) {
  1168. return $this->container->get('request_stack')->getCurrentRequest();
  1169. }
  1170. return $this->container->get('request');
  1171. }
  1172. }