CRUDController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. class CRUDController extends Controller
  20. {
  21. /**
  22. * The related Admin class
  23. *
  24. * @var \Sonata\AdminBundle\Admin\AdminInterface
  25. */
  26. protected $admin;
  27. /**
  28. * @param mixed $data
  29. * @param integer $status
  30. * @param array $headers
  31. *
  32. * @return Response with json encoded data
  33. */
  34. public function renderJson($data, $status = 200, $headers = array())
  35. {
  36. // fake content-type so browser does not show the download popup when this
  37. // response is rendered through an iframe (used by the jquery.form.js plugin)
  38. // => don't know yet if it is the best solution
  39. if ($this->get('request')->get('_xml_http_request')
  40. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  41. $headers['Content-Type'] = 'text/plain';
  42. } else {
  43. $headers['Content-Type'] = 'application/json';
  44. }
  45. return new Response(json_encode($data), $status, $headers);
  46. }
  47. /**
  48. *
  49. * @return boolean true if the request is done by an ajax like query
  50. */
  51. public function isXmlHttpRequest()
  52. {
  53. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  54. }
  55. /**
  56. * Sets the Container associated with this Controller.
  57. *
  58. * @param ContainerInterface $container A ContainerInterface instance
  59. */
  60. public function setContainer(ContainerInterface $container = null)
  61. {
  62. $this->container = $container;
  63. $this->configure();
  64. }
  65. /**
  66. * Contextualize the admin class depends on the current request
  67. *
  68. * @throws \RuntimeException
  69. * @return void
  70. */
  71. public function configure()
  72. {
  73. $adminCode = $this->container->get('request')->get('_sonata_admin');
  74. if (!$adminCode) {
  75. 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')));
  76. }
  77. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  78. if (!$this->admin) {
  79. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  80. }
  81. $rootAdmin = $this->admin;
  82. if ($this->admin->isChild()) {
  83. $this->admin->setCurrentChild(true);
  84. $rootAdmin = $rootAdmin->getParent();
  85. }
  86. $request = $this->container->get('request');
  87. $rootAdmin->setRequest($request);
  88. if ($request->get('uniqid')) {
  89. $this->admin->setUniqid($request->get('uniqid'));
  90. }
  91. }
  92. /**
  93. * return the base template name
  94. *
  95. * @return string the template name
  96. */
  97. public function getBaseTemplate()
  98. {
  99. if ($this->isXmlHttpRequest()) {
  100. return $this->admin->getTemplate('ajax');
  101. }
  102. return $this->admin->getTemplate('layout');
  103. }
  104. /**
  105. * @param $view
  106. * @param array $parameters
  107. * @param null|\Symfony\Component\HttpFoundation\Response $response
  108. * @return Response
  109. */
  110. public function render($view, array $parameters = array(), Response $response = null)
  111. {
  112. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  113. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  114. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  115. return parent::render($view, $parameters);
  116. }
  117. /**
  118. * return the Response object associated to the list action
  119. *
  120. * @return Response
  121. */
  122. public function listAction()
  123. {
  124. if (false === $this->admin->isGranted('LIST')) {
  125. throw new AccessDeniedException();
  126. }
  127. $datagrid = $this->admin->getDatagrid();
  128. $formView = $datagrid->getForm()->createView();
  129. // set the theme for the current Admin Form
  130. $this->get('twig')->getExtension('form')->setTheme($formView, $this->admin->getFilterTheme());
  131. return $this->render($this->admin->getListTemplate(), array(
  132. 'action' => 'list',
  133. 'form' => $formView,
  134. 'datagrid' => $datagrid
  135. ));
  136. }
  137. /**
  138. * execute a batch delete
  139. *
  140. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  141. * @param $query
  142. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  143. */
  144. public function batchActionDelete($query)
  145. {
  146. if (false === $this->admin->isGranted('DELETE')) {
  147. throw new AccessDeniedException();
  148. }
  149. $modelManager = $this->admin->getModelManager();
  150. try {
  151. $modelManager->batchDelete($this->admin->getClass(), $query);
  152. $this->get('session')->setFlash('sonata_flash_success', 'flash_batch_delete_success');
  153. } catch ( ModelManagerException $e ) {
  154. $this->get('session')->setFlash('sonata_flash_error', 'flash_batch_delete_error');
  155. }
  156. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  157. }
  158. /**
  159. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  160. * @param $id
  161. * @return Response|RedirectResponse
  162. */
  163. public function deleteAction($id)
  164. {
  165. $id = $this->get('request')->get($this->admin->getIdParameter());
  166. $object = $this->admin->getObject($id);
  167. if (!$object) {
  168. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  169. }
  170. if (false === $this->admin->isGranted('DELETE', $object)) {
  171. throw new AccessDeniedException();
  172. }
  173. if ($this->getRequest()->getMethod() == 'DELETE') {
  174. try {
  175. $this->admin->delete($object);
  176. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  177. } catch ( ModelManagerException $e ) {
  178. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  179. }
  180. return new RedirectResponse($this->admin->generateUrl('list'));
  181. }
  182. return $this->render('SonataAdminBundle:CRUD:delete.html.twig', array(
  183. 'object' => $object,
  184. 'action' => 'delete'
  185. ));
  186. }
  187. /**
  188. * return the Response object associated to the edit action
  189. *
  190. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  191. * @param mixed $id
  192. * @return \Symfony\Component\HttpFoundation\Response
  193. */
  194. public function editAction($id = null)
  195. {
  196. $id = $this->get('request')->get($this->admin->getIdParameter());
  197. $object = $this->admin->getObject($id);
  198. if (!$object) {
  199. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  200. }
  201. if (false === $this->admin->isGranted('EDIT', $object)) {
  202. throw new AccessDeniedException();
  203. }
  204. $this->admin->setSubject($object);
  205. $form = $this->admin->getForm();
  206. $form->setData($object);
  207. if ($this->get('request')->getMethod() == 'POST') {
  208. $form->bindRequest($this->get('request'));
  209. if ($form->isValid()) {
  210. $this->admin->update($object);
  211. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  212. if ($this->isXmlHttpRequest()) {
  213. return $this->renderJson(array(
  214. 'result' => 'ok',
  215. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  216. ));
  217. }
  218. // redirect to edit mode
  219. return $this->redirectTo($object);
  220. }
  221. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  222. }
  223. $view = $form->createView();
  224. // set the theme for the current Admin Form
  225. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  226. return $this->render($this->admin->getEditTemplate(), array(
  227. 'action' => 'edit',
  228. 'form' => $view,
  229. 'object' => $object,
  230. ));
  231. }
  232. /**
  233. * redirect the user depend on this choice
  234. *
  235. * @param object $object
  236. * @return \Symfony\Component\HttpFoundation\Response
  237. */
  238. public function redirectTo($object)
  239. {
  240. $url = false;
  241. if ($this->get('request')->get('btn_update_and_list')) {
  242. $url = $this->admin->generateUrl('list');
  243. }
  244. if ($this->get('request')->get('btn_create_and_create')) {
  245. $url = $this->admin->generateUrl('create');
  246. }
  247. if (!$url) {
  248. $url = $this->admin->generateObjectUrl('edit', $object);
  249. }
  250. return new RedirectResponse($url);
  251. }
  252. /**
  253. * return the Response object associated to the batch action
  254. *
  255. * @throws \RuntimeException
  256. * @return \Symfony\Component\HttpFoundation\Response
  257. */
  258. public function batchAction()
  259. {
  260. if ($this->get('request')->getMethod() != 'POST') {
  261. throw new \RuntimeException('invalid request type, POST expected');
  262. }
  263. $confirmation = $this->get('request')->get('confirmation', false);
  264. if ($data = json_decode($this->get('request')->get('data'), true)) {
  265. $action = $data['action'];
  266. $idx = $data['idx'];
  267. $all_elements = $data['all_elements'];
  268. $this->get('request')->request->replace($data);
  269. } else {
  270. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  271. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  272. $action = $this->get('request')->get('action');
  273. $idx = $this->get('request')->get('idx');
  274. $all_elements = $this->get('request')->get('all_elements');
  275. $data = $this->get('request')->request->all();
  276. }
  277. $batchActions = $this->admin->getBatchActions();
  278. if (!array_key_exists($action, $batchActions)) {
  279. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  280. }
  281. $camelizedAction = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  282. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  283. if (method_exists($this, $isRelevantAction)) {
  284. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  285. } else {
  286. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  287. }
  288. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  289. $nonRelevantMessage = 'flash_batch_empty';
  290. }
  291. if (true !== $nonRelevantMessage) {
  292. $this->get('session')->setFlash('sonata_flash_info', $nonRelevantMessage);
  293. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  294. }
  295. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  296. if ($askConfirmation && $confirmation != 'ok') {
  297. $datagrid = $this->admin->getDatagrid();
  298. $formView = $datagrid->getForm()->createView();
  299. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  300. 'action' => 'list',
  301. 'datagrid' => $datagrid,
  302. 'form' => $formView,
  303. 'data' => json_encode($data),
  304. ));
  305. }
  306. // execute the action, batchActionXxxxx
  307. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  308. if (!method_exists($this, $final_action)) {
  309. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  310. }
  311. $datagrid = $this->admin->getDatagrid();
  312. $datagrid->buildPager();
  313. $query = $datagrid->getQuery();
  314. $query->setFirstResult(null);
  315. $query->setMaxResults(null);
  316. if (count($idx) > 0) {
  317. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  318. } else if (!$all_elements) {
  319. $query = null;
  320. }
  321. return call_user_func(array($this, $final_action), $query);
  322. }
  323. /**
  324. * return the Response object associated to the create action
  325. *
  326. * @return \Symfony\Component\HttpFoundation\Response
  327. */
  328. public function createAction()
  329. {
  330. if (false === $this->admin->isGranted('CREATE')) {
  331. throw new AccessDeniedException();
  332. }
  333. $object = $this->admin->getNewInstance();
  334. $this->admin->setSubject($object);
  335. $form = $this->admin->getForm();
  336. $form->setData($object);
  337. if ($this->get('request')->getMethod() == 'POST') {
  338. $form->bindRequest($this->get('request'));
  339. if ($form->isValid()) {
  340. $this->admin->create($object);
  341. if ($this->isXmlHttpRequest()) {
  342. return $this->renderJson(array(
  343. 'result' => 'ok',
  344. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  345. ));
  346. }
  347. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  348. // redirect to edit mode
  349. return $this->redirectTo($object);
  350. }
  351. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  352. }
  353. $view = $form->createView();
  354. // set the theme for the current Admin Form
  355. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  356. return $this->render($this->admin->getEditTemplate(), array(
  357. 'action' => 'create',
  358. 'form' => $view,
  359. 'object' => $object,
  360. ));
  361. }
  362. /**
  363. * return the Response object associated to the view action
  364. *
  365. * @return \Symfony\Component\HttpFoundation\Response
  366. */
  367. public function showAction($id = null)
  368. {
  369. $id = $this->get('request')->get($this->admin->getIdParameter());
  370. $object = $this->admin->getObject($id);
  371. if (!$object) {
  372. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  373. }
  374. if (false === $this->admin->isGranted('VIEW', $object)) {
  375. throw new AccessDeniedException();
  376. }
  377. $this->admin->setSubject($object);
  378. return $this->render($this->admin->getShowTemplate(), array(
  379. 'action' => 'show',
  380. 'object' => $object,
  381. 'elements' => $this->admin->getShow(),
  382. ));
  383. }
  384. /**
  385. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  386. * @param mixed $id
  387. * @return Response
  388. */
  389. public function historyAction($id = null)
  390. {
  391. if (false === $this->admin->isGranted('EDIT')) {
  392. throw new AccessDeniedException();
  393. }
  394. $id = $this->get('request')->get($this->admin->getIdParameter());
  395. $object = $this->admin->getObject($id);
  396. if (!$object) {
  397. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  398. }
  399. $manager = $this->get('sonata.admin.audit.manager');
  400. if (!$manager->hasReader($this->admin->getClass())) {
  401. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  402. }
  403. $reader = $manager->getReader($this->admin->getClass());
  404. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  405. return $this->render($this->admin->getTemplate('history'), array(
  406. 'action' => 'history',
  407. 'object' => $object,
  408. 'revisions' => $revisions,
  409. ));
  410. }
  411. /**
  412. * @param null $id
  413. * @param $revision
  414. * @return Response
  415. */
  416. public function historyViewRevisionAction($id = null, $revision = null)
  417. {
  418. if (false === $this->admin->isGranted('EDIT')) {
  419. throw new AccessDeniedException();
  420. }
  421. $id = $this->get('request')->get($this->admin->getIdParameter());
  422. $object = $this->admin->getObject($id);
  423. if (!$object) {
  424. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  425. }
  426. $manager = $this->get('sonata.admin.audit.manager');
  427. if (!$manager->hasReader($this->admin->getClass())) {
  428. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  429. }
  430. $reader = $manager->getReader($this->admin->getClass());
  431. // retrieve the revisioned object
  432. $object = $reader->find($this->admin->getClass(), $id, $revision);
  433. if (!$object) {
  434. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  435. }
  436. $this->admin->setSubject($object);
  437. return $this->render($this->admin->getShowTemplate(), array(
  438. 'action' => 'show',
  439. 'object' => $object,
  440. 'elements' => $this->admin->getShow(),
  441. ));
  442. }
  443. /**
  444. * @param \Symfony\Component\HttpFoundation\Request $request
  445. * @return \Symfony\Component\HttpFoundation\Response
  446. */
  447. public function exportAction(Request $request)
  448. {
  449. $format = $request->get('format');
  450. $allowedExportFormats = (array) $this->admin->getExportFormats();
  451. if(!in_array($format, $allowedExportFormats) ) {
  452. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  453. }
  454. $filename = sprintf('export_%s_%s.%s',
  455. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  456. date('Y_m_d_H_i_s', strtotime('now')),
  457. $format
  458. );
  459. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  460. }
  461. }