CRUDController.php 22 KB

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