CRUDController.php 22 KB

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