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 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 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->setTemplate('edit', $this->admin->getTemplate('preview'));
  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 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. $params = array();
  263. if ($this->admin->hasActiveSubClass()) {
  264. $params['subclass'] = $this->get('request')->get('subclass');
  265. }
  266. $url = $this->admin->generateUrl('create', $params);
  267. }
  268. if (!$url) {
  269. $url = $this->admin->generateObjectUrl('edit', $object);
  270. }
  271. return new RedirectResponse($url);
  272. }
  273. /**
  274. * return the Response object associated to the batch action
  275. *
  276. * @throws \RuntimeException
  277. * @return Response
  278. */
  279. public function batchAction()
  280. {
  281. if ($this->get('request')->getMethod() != 'POST') {
  282. throw new \RuntimeException('invalid request type, POST expected');
  283. }
  284. $confirmation = $this->get('request')->get('confirmation', false);
  285. if ($data = json_decode($this->get('request')->get('data'), true)) {
  286. $action = $data['action'];
  287. $idx = $data['idx'];
  288. $all_elements = $data['all_elements'];
  289. $this->get('request')->request->replace($data);
  290. } else {
  291. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  292. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  293. $action = $this->get('request')->get('action');
  294. $idx = $this->get('request')->get('idx');
  295. $all_elements = $this->get('request')->get('all_elements');
  296. $data = $this->get('request')->request->all();
  297. }
  298. $batchActions = $this->admin->getBatchActions();
  299. if (!array_key_exists($action, $batchActions)) {
  300. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  301. }
  302. $camelizedAction = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  303. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  304. if (method_exists($this, $isRelevantAction)) {
  305. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  306. } else {
  307. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  308. }
  309. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  310. $nonRelevantMessage = 'flash_batch_empty';
  311. }
  312. if (true !== $nonRelevantMessage) {
  313. $this->get('session')->setFlash('sonata_flash_info', $nonRelevantMessage);
  314. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  315. }
  316. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  317. if ($askConfirmation && $confirmation != 'ok') {
  318. $datagrid = $this->admin->getDatagrid();
  319. $formView = $datagrid->getForm()->createView();
  320. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  321. 'action' => 'list',
  322. 'datagrid' => $datagrid,
  323. 'form' => $formView,
  324. 'data' => $data,
  325. ));
  326. }
  327. // execute the action, batchActionXxxxx
  328. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  329. if (!method_exists($this, $final_action)) {
  330. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  331. }
  332. $datagrid = $this->admin->getDatagrid();
  333. $datagrid->buildPager();
  334. $query = $datagrid->getQuery();
  335. $query->setFirstResult(null);
  336. $query->setMaxResults(null);
  337. if (count($idx) > 0) {
  338. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  339. } else if (!$all_elements) {
  340. $query = null;
  341. }
  342. return call_user_func(array($this, $final_action), $query);
  343. }
  344. /**
  345. * return the Response object associated to the create action
  346. *
  347. * @return Response
  348. */
  349. public function createAction()
  350. {
  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. // enable the preview template if the form was valid and preview was requested
  379. $this->admin->setTemplate('edit', $this->admin->getTemplate('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->getEditTemplate(), 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->isPreviewRequested() || $this->isPreviewApproved() || $this->isPreviewDeclined());
  420. }
  421. /**
  422. * Returns true if the preview has been declined
  423. *
  424. * @return boolean
  425. */
  426. protected function isPreviewDeclined()
  427. {
  428. return ($this->get('request')->get('btn_preview_decline') !== null);
  429. }
  430. /**
  431. * return the Response object associated to the view action
  432. *
  433. * @return Response
  434. */
  435. public function showAction($id = null)
  436. {
  437. $id = $this->get('request')->get($this->admin->getIdParameter());
  438. $object = $this->admin->getObject($id);
  439. if (!$object) {
  440. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  441. }
  442. if (false === $this->admin->isGranted('VIEW', $object)) {
  443. throw new AccessDeniedException();
  444. }
  445. $this->admin->setSubject($object);
  446. return $this->render($this->admin->getShowTemplate(), array(
  447. 'action' => 'show',
  448. 'object' => $object,
  449. 'elements' => $this->admin->getShow(),
  450. ));
  451. }
  452. /**
  453. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  454. *
  455. * @param mixed $id
  456. *
  457. * @return Response
  458. */
  459. public function historyAction($id = null)
  460. {
  461. if (false === $this->admin->isGranted('EDIT')) {
  462. throw new AccessDeniedException();
  463. }
  464. $id = $this->get('request')->get($this->admin->getIdParameter());
  465. $object = $this->admin->getObject($id);
  466. if (!$object) {
  467. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  468. }
  469. $manager = $this->get('sonata.admin.audit.manager');
  470. if (!$manager->hasReader($this->admin->getClass())) {
  471. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  472. }
  473. $reader = $manager->getReader($this->admin->getClass());
  474. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  475. return $this->render($this->admin->getTemplate('history'), array(
  476. 'action' => 'history',
  477. 'object' => $object,
  478. 'revisions' => $revisions,
  479. ));
  480. }
  481. /**
  482. * @param null $id
  483. * @param string $revision
  484. *
  485. * @return Response
  486. */
  487. public function historyViewRevisionAction($id = null, $revision = null)
  488. {
  489. if (false === $this->admin->isGranted('EDIT')) {
  490. throw new AccessDeniedException();
  491. }
  492. $id = $this->get('request')->get($this->admin->getIdParameter());
  493. $object = $this->admin->getObject($id);
  494. if (!$object) {
  495. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  496. }
  497. $manager = $this->get('sonata.admin.audit.manager');
  498. if (!$manager->hasReader($this->admin->getClass())) {
  499. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  500. }
  501. $reader = $manager->getReader($this->admin->getClass());
  502. // retrieve the revisioned object
  503. $object = $reader->find($this->admin->getClass(), $id, $revision);
  504. if (!$object) {
  505. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  506. }
  507. $this->admin->setSubject($object);
  508. return $this->render($this->admin->getShowTemplate(), array(
  509. 'action' => 'show',
  510. 'object' => $object,
  511. 'elements' => $this->admin->getShow(),
  512. ));
  513. }
  514. /**
  515. * @param Request $request
  516. *
  517. * @return Response
  518. */
  519. public function exportAction(Request $request)
  520. {
  521. if (false === $this->admin->isGranted('EXPORT')) {
  522. throw new AccessDeniedException();
  523. }
  524. $format = $request->get('format');
  525. $allowedExportFormats = (array) $this->admin->getExportFormats();
  526. if(!in_array($format, $allowedExportFormats) ) {
  527. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  528. }
  529. $filename = sprintf('export_%s_%s.%s',
  530. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  531. date('Y_m_d_H_i_s', strtotime('now')),
  532. $format
  533. );
  534. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  535. }
  536. }