CRUDController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Controller;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  20. class CRUDController extends Controller
  21. {
  22. /**
  23. * The related Admin class
  24. *
  25. * @var \Sonata\AdminBundle\Admin\AdminInterface
  26. */
  27. protected $admin;
  28. /**
  29. * @param mixed $data
  30. * @param integer $status
  31. * @param array $headers
  32. *
  33. * @return Response with json encoded data
  34. */
  35. public function renderJson($data, $status = 200, $headers = array())
  36. {
  37. // fake content-type so browser does not show the download popup when this
  38. // response is rendered through an iframe (used by the jquery.form.js plugin)
  39. // => don't know yet if it is the best solution
  40. if ($this->get('request')->get('_xml_http_request')
  41. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  42. $headers['Content-Type'] = 'text/plain';
  43. } else {
  44. $headers['Content-Type'] = 'application/json';
  45. }
  46. return new Response(json_encode($data), $status, $headers);
  47. }
  48. /**
  49. *
  50. * @return boolean true if the request is done by an ajax like query
  51. */
  52. public function isXmlHttpRequest()
  53. {
  54. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  55. }
  56. /**
  57. * Sets the Container associated with this Controller.
  58. *
  59. * @param ContainerInterface $container A ContainerInterface instance
  60. */
  61. public function setContainer(ContainerInterface $container = null)
  62. {
  63. $this->container = $container;
  64. $this->configure();
  65. }
  66. /**
  67. * Contextualize the admin class depends on the current request
  68. *
  69. * @throws \RuntimeException
  70. * @return void
  71. */
  72. public function configure()
  73. {
  74. $adminCode = $this->container->get('request')->get('_sonata_admin');
  75. if (!$adminCode) {
  76. throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $this->container->get('request')->get('_route')));
  77. }
  78. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  79. if (!$this->admin) {
  80. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  81. }
  82. $rootAdmin = $this->admin;
  83. if ($this->admin->isChild()) {
  84. $this->admin->setCurrentChild(true);
  85. $rootAdmin = $rootAdmin->getParent();
  86. }
  87. $request = $this->container->get('request');
  88. $rootAdmin->setRequest($request);
  89. if ($request->get('uniqid')) {
  90. $this->admin->setUniqid($request->get('uniqid'));
  91. }
  92. }
  93. /**
  94. * return the base template name
  95. *
  96. * @return string the template name
  97. */
  98. public function getBaseTemplate()
  99. {
  100. if ($this->isXmlHttpRequest()) {
  101. return $this->admin->getTemplate('ajax');
  102. }
  103. return $this->admin->getTemplate('layout');
  104. }
  105. /**
  106. * @param string $view
  107. * @param array $parameters
  108. * @param Response $response
  109. *
  110. * @return Response
  111. */
  112. public function render($view, array $parameters = array(), Response $response = null)
  113. {
  114. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  115. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  116. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  117. return parent::render($view, $parameters);
  118. }
  119. /**
  120. * return the Response object associated to the list action
  121. *
  122. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  123. *
  124. * @return Response
  125. */
  126. public function listAction()
  127. {
  128. if (false === $this->admin->isGranted('LIST')) {
  129. throw new AccessDeniedException();
  130. }
  131. $datagrid = $this->admin->getDatagrid();
  132. $formView = $datagrid->getForm()->createView();
  133. // set the theme for the current Admin Form
  134. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  135. return $this->render($this->admin->getTemplate('list'), array(
  136. 'action' => 'list',
  137. 'form' => $formView,
  138. 'datagrid' => $datagrid
  139. ));
  140. }
  141. /**
  142. * execute a batch delete
  143. *
  144. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  145. *
  146. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $query
  147. *
  148. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  149. */
  150. public function batchActionDelete(ProxyQueryInterface $query)
  151. {
  152. if (false === $this->admin->isGranted('DELETE')) {
  153. throw new AccessDeniedException();
  154. }
  155. $modelManager = $this->admin->getModelManager();
  156. try {
  157. $modelManager->batchDelete($this->admin->getClass(), $query);
  158. $this->get('session')->setFlash('sonata_flash_success', 'flash_batch_delete_success');
  159. } catch ( ModelManagerException $e ) {
  160. $this->get('session')->setFlash('sonata_flash_error', 'flash_batch_delete_error');
  161. }
  162. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  163. }
  164. /**
  165. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  166. *
  167. * @param mixed $id
  168. *
  169. * @return Response|RedirectResponse
  170. */
  171. public function deleteAction($id)
  172. {
  173. $id = $this->get('request')->get($this->admin->getIdParameter());
  174. $object = $this->admin->getObject($id);
  175. if (!$object) {
  176. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  177. }
  178. if (false === $this->admin->isGranted('DELETE', $object)) {
  179. throw new AccessDeniedException();
  180. }
  181. if ($this->getRequest()->getMethod() == 'DELETE') {
  182. try {
  183. $this->admin->delete($object);
  184. if ($this->isXmlHttpRequest()) {
  185. return $this->renderJson(array('result' => 'ok'));
  186. }
  187. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  188. } catch (ModelManagerException $e) {
  189. if ($this->isXmlHttpRequest()) {
  190. return $this->renderJson(array('result' => 'error'));
  191. }
  192. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  193. }
  194. return new RedirectResponse($this->admin->generateUrl('list'));
  195. }
  196. return $this->render($this->admin->getTemplate('delete'), array(
  197. 'object' => $object,
  198. 'action' => 'delete'
  199. ));
  200. }
  201. /**
  202. * return the Response object associated to the edit action
  203. *
  204. *
  205. * @param mixed $id
  206. *
  207. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  208. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  209. *
  210. * @return Response
  211. */
  212. public function editAction($id = null)
  213. {
  214. // the key used to lookup the template
  215. $templateKey = 'edit';
  216. $id = $this->get('request')->get($this->admin->getIdParameter());
  217. $object = $this->admin->getObject($id);
  218. if (!$object) {
  219. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  220. }
  221. if (false === $this->admin->isGranted('EDIT', $object)) {
  222. throw new AccessDeniedException();
  223. }
  224. $this->admin->setSubject($object);
  225. /** @var $form \Symfony\Component\Form\Form */
  226. $form = $this->admin->getForm();
  227. $form->setData($object);
  228. if ($this->get('request')->getMethod() == 'POST') {
  229. $form->bind($this->get('request'));
  230. $isFormValid = $form->isValid();
  231. // persist if the form was valid and if in preview mode the preview was approved
  232. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  233. $this->admin->update($object);
  234. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  235. if ($this->isXmlHttpRequest()) {
  236. return $this->renderJson(array(
  237. 'result' => 'ok',
  238. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  239. ));
  240. }
  241. // redirect to edit mode
  242. return $this->redirectTo($object);
  243. }
  244. // show an error message if the form failed validation
  245. if (!$isFormValid) {
  246. if (!$this->isXmlHttpRequest()) {
  247. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  248. }
  249. } elseif ($this->isPreviewRequested()) {
  250. // enable the preview template if the form was valid and preview was requested
  251. $templateKey = 'preview';
  252. }
  253. }
  254. $view = $form->createView();
  255. // set the theme for the current Admin Form
  256. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  257. return $this->render($this->admin->getTemplate($templateKey), array(
  258. 'action' => 'edit',
  259. 'form' => $view,
  260. 'object' => $object,
  261. ));
  262. }
  263. /**
  264. * redirect the user depend on this choice
  265. *
  266. * @param object $object
  267. *
  268. * @return Response
  269. */
  270. public function redirectTo($object)
  271. {
  272. $url = false;
  273. if ($this->get('request')->get('btn_update_and_list')) {
  274. $url = $this->admin->generateUrl('list');
  275. }
  276. if ($this->get('request')->get('btn_create_and_list')) {
  277. $url = $this->admin->generateUrl('list');
  278. }
  279. if ($this->get('request')->get('btn_create_and_create')) {
  280. $params = array();
  281. if ($this->admin->hasActiveSubClass()) {
  282. $params['subclass'] = $this->get('request')->get('subclass');
  283. }
  284. $url = $this->admin->generateUrl('create', $params);
  285. }
  286. if (!$url) {
  287. $url = $this->admin->generateObjectUrl('edit', $object);
  288. }
  289. return new RedirectResponse($url);
  290. }
  291. /**
  292. * return the Response object associated to the batch action
  293. *
  294. * @throws \RuntimeException
  295. * @return Response
  296. */
  297. public function batchAction()
  298. {
  299. if ($this->get('request')->getMethod() != 'POST') {
  300. throw new \RuntimeException('invalid request type, POST expected');
  301. }
  302. $confirmation = $this->get('request')->get('confirmation', false);
  303. if ($data = json_decode($this->get('request')->get('data'), true)) {
  304. $action = $data['action'];
  305. $idx = $data['idx'];
  306. $all_elements = $data['all_elements'];
  307. $this->get('request')->request->replace($data);
  308. } else {
  309. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  310. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  311. $action = $this->get('request')->get('action');
  312. $idx = $this->get('request')->get('idx');
  313. $all_elements = $this->get('request')->get('all_elements');
  314. $data = $this->get('request')->request->all();
  315. }
  316. $batchActions = $this->admin->getBatchActions();
  317. if (!array_key_exists($action, $batchActions)) {
  318. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  319. }
  320. $camelizedAction = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  321. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  322. if (method_exists($this, $isRelevantAction)) {
  323. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  324. } else {
  325. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  326. }
  327. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  328. $nonRelevantMessage = 'flash_batch_empty';
  329. }
  330. $datagrid = $this->admin->getDatagrid();
  331. $datagrid->buildPager();
  332. if (true !== $nonRelevantMessage) {
  333. $this->get('session')->setFlash('sonata_flash_info', $nonRelevantMessage);
  334. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  335. }
  336. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  337. if ($askConfirmation && $confirmation != 'ok') {
  338. $formView = $datagrid->getForm()->createView();
  339. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  340. 'action' => 'list',
  341. 'datagrid' => $datagrid,
  342. 'form' => $formView,
  343. 'data' => $data,
  344. ));
  345. }
  346. // execute the action, batchActionXxxxx
  347. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  348. if (!method_exists($this, $final_action)) {
  349. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  350. }
  351. $query = $datagrid->getQuery();
  352. $query->setFirstResult(null);
  353. $query->setMaxResults(null);
  354. if (count($idx) > 0) {
  355. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  356. } elseif (!$all_elements) {
  357. $query = null;
  358. }
  359. return call_user_func(array($this, $final_action), $query);
  360. }
  361. /**
  362. * return the Response object associated to the create action
  363. *
  364. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  365. * @return Response
  366. */
  367. public function createAction()
  368. {
  369. // the key used to lookup the template
  370. $templateKey = 'edit';
  371. if (false === $this->admin->isGranted('CREATE')) {
  372. throw new AccessDeniedException();
  373. }
  374. $object = $this->admin->getNewInstance();
  375. $this->admin->setSubject($object);
  376. /** @var $form \Symfony\Component\Form\Form */
  377. $form = $this->admin->getForm();
  378. $form->setData($object);
  379. if ($this->get('request')->getMethod() == 'POST') {
  380. $form->bind($this->get('request'));
  381. $isFormValid = $form->isValid();
  382. // persist if the form was valid and if in preview mode the preview was approved
  383. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  384. $this->admin->create($object);
  385. if ($this->isXmlHttpRequest()) {
  386. return $this->renderJson(array(
  387. 'result' => 'ok',
  388. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  389. ));
  390. }
  391. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  392. // redirect to edit mode
  393. return $this->redirectTo($object);
  394. }
  395. // show an error message if the form failed validation
  396. if (!$isFormValid) {
  397. if (!$this->isXmlHttpRequest()) {
  398. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  399. }
  400. } elseif ($this->isPreviewRequested()) {
  401. // pick the preview template if the form was valid and preview was requested
  402. $templateKey = 'preview';
  403. }
  404. }
  405. $view = $form->createView();
  406. // set the theme for the current Admin Form
  407. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  408. return $this->render($this->admin->getTemplate($templateKey), array(
  409. 'action' => 'create',
  410. 'form' => $view,
  411. 'object' => $object,
  412. ));
  413. }
  414. /**
  415. * Returns true if the preview is requested to be shown
  416. *
  417. * @return boolean
  418. */
  419. protected function isPreviewRequested()
  420. {
  421. return ($this->get('request')->get('btn_preview') !== null);
  422. }
  423. /**
  424. * Returns true if the preview has been approved
  425. *
  426. * @return boolean
  427. */
  428. protected function isPreviewApproved()
  429. {
  430. return ($this->get('request')->get('btn_preview_approve') !== null);
  431. }
  432. /**
  433. * Returns true if the request is in the preview workflow
  434. *
  435. * That means either a preview is requested or the preview has already been shown
  436. * and it got approved/declined.
  437. *
  438. * @return boolean
  439. */
  440. protected function isInPreviewMode()
  441. {
  442. return $this->admin->supportsPreviewMode()
  443. && ($this->isPreviewRequested()
  444. || $this->isPreviewApproved()
  445. || $this->isPreviewDeclined());
  446. }
  447. /**
  448. * Returns true if the preview has been declined
  449. *
  450. * @return boolean
  451. */
  452. protected function isPreviewDeclined()
  453. {
  454. return ($this->get('request')->get('btn_preview_decline') !== null);
  455. }
  456. /**
  457. * return the Response object associated to the view action
  458. *
  459. * @param null $id
  460. *
  461. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  462. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  463. *
  464. * @return Response
  465. */
  466. public function showAction($id = null)
  467. {
  468. $id = $this->get('request')->get($this->admin->getIdParameter());
  469. $object = $this->admin->getObject($id);
  470. if (!$object) {
  471. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  472. }
  473. if (false === $this->admin->isGranted('VIEW', $object)) {
  474. throw new AccessDeniedException();
  475. }
  476. $this->admin->setSubject($object);
  477. return $this->render($this->admin->getTemplate('show'), array(
  478. 'action' => 'show',
  479. 'object' => $object,
  480. 'elements' => $this->admin->getShow(),
  481. ));
  482. }
  483. /**
  484. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  485. *
  486. * @param mixed $id
  487. *
  488. * @return Response
  489. */
  490. public function historyAction($id = null)
  491. {
  492. if (false === $this->admin->isGranted('EDIT')) {
  493. throw new AccessDeniedException();
  494. }
  495. $id = $this->get('request')->get($this->admin->getIdParameter());
  496. $object = $this->admin->getObject($id);
  497. if (!$object) {
  498. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  499. }
  500. $manager = $this->get('sonata.admin.audit.manager');
  501. if (!$manager->hasReader($this->admin->getClass())) {
  502. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  503. }
  504. $reader = $manager->getReader($this->admin->getClass());
  505. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  506. return $this->render($this->admin->getTemplate('history'), array(
  507. 'action' => 'history',
  508. 'object' => $object,
  509. 'revisions' => $revisions,
  510. ));
  511. }
  512. /**
  513. * @param null $id
  514. * @param string $revision
  515. *
  516. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  517. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  518. *
  519. * @return Response
  520. */
  521. public function historyViewRevisionAction($id = null, $revision = null)
  522. {
  523. if (false === $this->admin->isGranted('EDIT')) {
  524. throw new AccessDeniedException();
  525. }
  526. $id = $this->get('request')->get($this->admin->getIdParameter());
  527. $object = $this->admin->getObject($id);
  528. if (!$object) {
  529. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  530. }
  531. $manager = $this->get('sonata.admin.audit.manager');
  532. if (!$manager->hasReader($this->admin->getClass())) {
  533. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  534. }
  535. $reader = $manager->getReader($this->admin->getClass());
  536. // retrieve the revisioned object
  537. $object = $reader->find($this->admin->getClass(), $id, $revision);
  538. if (!$object) {
  539. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  540. }
  541. $this->admin->setSubject($object);
  542. return $this->render($this->admin->getTemplate('show'), array(
  543. 'action' => 'show',
  544. 'object' => $object,
  545. 'elements' => $this->admin->getShow(),
  546. ));
  547. }
  548. /**
  549. * @param Request $request
  550. *
  551. * @throws \RuntimeException
  552. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  553. *
  554. * @return Response
  555. */
  556. public function exportAction(Request $request)
  557. {
  558. if (false === $this->admin->isGranted('EXPORT')) {
  559. throw new AccessDeniedException();
  560. }
  561. $format = $request->get('format');
  562. $allowedExportFormats = (array) $this->admin->getExportFormats();
  563. if (!in_array($format, $allowedExportFormats) ) {
  564. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  565. }
  566. $filename = sprintf('export_%s_%s.%s',
  567. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  568. date('Y_m_d_H_i_s', strtotime('now')),
  569. $format
  570. );
  571. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  572. }
  573. }