CRUDController.php 22 KB

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