CRUDController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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', $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. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  185. } catch (ModelManagerException $e) {
  186. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  187. }
  188. return new RedirectResponse($this->admin->generateUrl('list'));
  189. }
  190. return $this->render($this->admin->getTemplate('delete'), array(
  191. 'object' => $object,
  192. 'action' => 'delete'
  193. ));
  194. }
  195. /**
  196. * return the Response object associated to the edit action
  197. *
  198. *
  199. * @param mixed $id
  200. *
  201. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  202. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  203. *
  204. * @return Response
  205. */
  206. public function editAction($id = null)
  207. {
  208. // the key used to lookup the template
  209. $templateKey = 'edit';
  210. $id = $this->get('request')->get($this->admin->getIdParameter());
  211. $object = $this->admin->getObject($id);
  212. if (!$object) {
  213. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  214. }
  215. if (false === $this->admin->isGranted('EDIT', $object)) {
  216. throw new AccessDeniedException();
  217. }
  218. $this->admin->setSubject($object);
  219. /** @var $form \Symfony\Component\Form\Form */
  220. $form = $this->admin->getForm();
  221. $form->setData($object);
  222. if ($this->get('request')->getMethod() == 'POST') {
  223. $form->bind($this->get('request'));
  224. $isFormValid = $form->isValid();
  225. // persist if the form was valid and if in preview mode the preview was approved
  226. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  227. $this->admin->update($object);
  228. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  229. if ($this->isXmlHttpRequest()) {
  230. return $this->renderJson(array(
  231. 'result' => 'ok',
  232. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  233. ));
  234. }
  235. // redirect to edit mode
  236. return $this->redirectTo($object);
  237. }
  238. // show an error message if the form failed validation
  239. if (!$isFormValid) {
  240. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  241. } elseif ($this->isPreviewRequested()) {
  242. // enable the preview template if the form was valid and preview was requested
  243. $templateKey = 'preview';
  244. }
  245. }
  246. $view = $form->createView();
  247. // set the theme for the current Admin Form
  248. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  249. return $this->render($this->admin->getTemplate($templateKey), array(
  250. 'action' => 'edit',
  251. 'form' => $view,
  252. 'object' => $object,
  253. ));
  254. }
  255. /**
  256. * redirect the user depend on this choice
  257. *
  258. * @param object $object
  259. *
  260. * @return Response
  261. */
  262. public function redirectTo($object)
  263. {
  264. $url = false;
  265. if ($this->get('request')->get('btn_update_and_list')) {
  266. $url = $this->admin->generateUrl('list');
  267. }
  268. if ($this->get('request')->get('btn_create_and_list')) {
  269. $url = $this->admin->generateUrl('list');
  270. }
  271. if ($this->get('request')->get('btn_create_and_create')) {
  272. $params = array();
  273. if ($this->admin->hasActiveSubClass()) {
  274. $params['subclass'] = $this->get('request')->get('subclass');
  275. }
  276. $url = $this->admin->generateUrl('create', $params);
  277. }
  278. if (!$url) {
  279. $url = $this->admin->generateObjectUrl('edit', $object);
  280. }
  281. return new RedirectResponse($url);
  282. }
  283. /**
  284. * return the Response object associated to the batch action
  285. *
  286. * @throws \RuntimeException
  287. * @return Response
  288. */
  289. public function batchAction()
  290. {
  291. if ($this->get('request')->getMethod() != 'POST') {
  292. throw new \RuntimeException('invalid request type, POST expected');
  293. }
  294. $confirmation = $this->get('request')->get('confirmation', false);
  295. if ($data = json_decode($this->get('request')->get('data'), true)) {
  296. $action = $data['action'];
  297. $idx = $data['idx'];
  298. $all_elements = $data['all_elements'];
  299. $this->get('request')->request->replace($data);
  300. } else {
  301. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  302. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  303. $action = $this->get('request')->get('action');
  304. $idx = $this->get('request')->get('idx');
  305. $all_elements = $this->get('request')->get('all_elements');
  306. $data = $this->get('request')->request->all();
  307. }
  308. $batchActions = $this->admin->getBatchActions();
  309. if (!array_key_exists($action, $batchActions)) {
  310. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  311. }
  312. $camelizedAction = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  313. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  314. if (method_exists($this, $isRelevantAction)) {
  315. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  316. } else {
  317. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  318. }
  319. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  320. $nonRelevantMessage = 'flash_batch_empty';
  321. }
  322. if (true !== $nonRelevantMessage) {
  323. $this->get('session')->setFlash('sonata_flash_info', $nonRelevantMessage);
  324. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  325. }
  326. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  327. if ($askConfirmation && $confirmation != 'ok') {
  328. $datagrid = $this->admin->getDatagrid();
  329. $formView = $datagrid->getForm()->createView();
  330. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  331. 'action' => 'list',
  332. 'datagrid' => $datagrid,
  333. 'form' => $formView,
  334. 'data' => $data,
  335. ));
  336. }
  337. // execute the action, batchActionXxxxx
  338. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  339. if (!method_exists($this, $final_action)) {
  340. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  341. }
  342. $datagrid = $this->admin->getDatagrid();
  343. $datagrid->buildPager();
  344. $query = $datagrid->getQuery();
  345. $query->setFirstResult(null);
  346. $query->setMaxResults(null);
  347. if (count($idx) > 0) {
  348. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  349. } else if (!$all_elements) {
  350. $query = null;
  351. }
  352. return call_user_func(array($this, $final_action), $query);
  353. }
  354. /**
  355. * return the Response object associated to the create action
  356. *
  357. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  358. * @return Response
  359. */
  360. public function createAction()
  361. {
  362. // the key used to lookup the template
  363. $templateKey = 'edit';
  364. if (false === $this->admin->isGranted('CREATE')) {
  365. throw new AccessDeniedException();
  366. }
  367. $object = $this->admin->getNewInstance();
  368. $this->admin->setSubject($object);
  369. /** @var $form \Symfony\Component\Form\Form */
  370. $form = $this->admin->getForm();
  371. $form->setData($object);
  372. if ($this->get('request')->getMethod() == 'POST') {
  373. $form->bind($this->get('request'));
  374. $isFormValid = $form->isValid();
  375. // persist if the form was valid and if in preview mode the preview was approved
  376. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  377. $this->admin->create($object);
  378. if ($this->isXmlHttpRequest()) {
  379. return $this->renderJson(array(
  380. 'result' => 'ok',
  381. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  382. ));
  383. }
  384. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  385. // redirect to edit mode
  386. return $this->redirectTo($object);
  387. }
  388. // show an error message if the form failed validation
  389. if (!$isFormValid) {
  390. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  391. } elseif ($this->isPreviewRequested()) {
  392. // pick the preview template if the form was valid and preview was requested
  393. $templateKey = 'preview';
  394. }
  395. }
  396. $view = $form->createView();
  397. // set the theme for the current Admin Form
  398. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  399. return $this->render($this->admin->getTemplate($templateKey), array(
  400. 'action' => 'create',
  401. 'form' => $view,
  402. 'object' => $object,
  403. ));
  404. }
  405. /**
  406. * Returns true if the preview is requested to be shown
  407. *
  408. * @return boolean
  409. */
  410. protected function isPreviewRequested()
  411. {
  412. return ($this->get('request')->get('btn_preview') !== null);
  413. }
  414. /**
  415. * Returns true if the preview has been approved
  416. *
  417. * @return boolean
  418. */
  419. protected function isPreviewApproved()
  420. {
  421. return ($this->get('request')->get('btn_preview_approve') !== null);
  422. }
  423. /**
  424. * Returns true if the request is in the preview workflow
  425. *
  426. * That means either a preview is requested or the preview has already been shown
  427. * and it got approved/declined.
  428. *
  429. * @return boolean
  430. */
  431. protected function isInPreviewMode()
  432. {
  433. return $this->admin->supportsPreviewMode()
  434. && ($this->isPreviewRequested()
  435. || $this->isPreviewApproved()
  436. || $this->isPreviewDeclined());
  437. }
  438. /**
  439. * Returns true if the preview has been declined
  440. *
  441. * @return boolean
  442. */
  443. protected function isPreviewDeclined()
  444. {
  445. return ($this->get('request')->get('btn_preview_decline') !== null);
  446. }
  447. /**
  448. * return the Response object associated to the view action
  449. *
  450. * @param null $id
  451. *
  452. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  453. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  454. *
  455. * @return Response
  456. */
  457. public function showAction($id = null)
  458. {
  459. $id = $this->get('request')->get($this->admin->getIdParameter());
  460. $object = $this->admin->getObject($id);
  461. if (!$object) {
  462. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  463. }
  464. if (false === $this->admin->isGranted('VIEW', $object)) {
  465. throw new AccessDeniedException();
  466. }
  467. $this->admin->setSubject($object);
  468. return $this->render($this->admin->getTemplate('show'), array(
  469. 'action' => 'show',
  470. 'object' => $object,
  471. 'elements' => $this->admin->getShow(),
  472. ));
  473. }
  474. /**
  475. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  476. *
  477. * @param mixed $id
  478. *
  479. * @return Response
  480. */
  481. public function historyAction($id = null)
  482. {
  483. if (false === $this->admin->isGranted('EDIT')) {
  484. throw new AccessDeniedException();
  485. }
  486. $id = $this->get('request')->get($this->admin->getIdParameter());
  487. $object = $this->admin->getObject($id);
  488. if (!$object) {
  489. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  490. }
  491. $manager = $this->get('sonata.admin.audit.manager');
  492. if (!$manager->hasReader($this->admin->getClass())) {
  493. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  494. }
  495. $reader = $manager->getReader($this->admin->getClass());
  496. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  497. return $this->render($this->admin->getTemplate('history'), array(
  498. 'action' => 'history',
  499. 'object' => $object,
  500. 'revisions' => $revisions,
  501. ));
  502. }
  503. /**
  504. * @param null $id
  505. * @param string $revision
  506. *
  507. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  508. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  509. *
  510. * @return Response
  511. */
  512. public function historyViewRevisionAction($id = null, $revision = null)
  513. {
  514. if (false === $this->admin->isGranted('EDIT')) {
  515. throw new AccessDeniedException();
  516. }
  517. $id = $this->get('request')->get($this->admin->getIdParameter());
  518. $object = $this->admin->getObject($id);
  519. if (!$object) {
  520. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  521. }
  522. $manager = $this->get('sonata.admin.audit.manager');
  523. if (!$manager->hasReader($this->admin->getClass())) {
  524. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  525. }
  526. $reader = $manager->getReader($this->admin->getClass());
  527. // retrieve the revisioned object
  528. $object = $reader->find($this->admin->getClass(), $id, $revision);
  529. if (!$object) {
  530. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  531. }
  532. $this->admin->setSubject($object);
  533. return $this->render($this->admin->getTemplate('show'), array(
  534. 'action' => 'show',
  535. 'object' => $object,
  536. 'elements' => $this->admin->getShow(),
  537. ));
  538. }
  539. /**
  540. * @param Request $request
  541. *
  542. * @throws \RuntimeException
  543. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  544. *
  545. * @return Response
  546. */
  547. public function exportAction(Request $request)
  548. {
  549. if (false === $this->admin->isGranted('EXPORT')) {
  550. throw new AccessDeniedException();
  551. }
  552. $format = $request->get('format');
  553. $allowedExportFormats = (array) $this->admin->getExportFormats();
  554. if(!in_array($format, $allowedExportFormats) ) {
  555. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  556. }
  557. $filename = sprintf('export_%s_%s.%s',
  558. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  559. date('Y_m_d_H_i_s', strtotime('now')),
  560. $format
  561. );
  562. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  563. }
  564. }