CRUDController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 \Symfony\Bundle\FrameworkBundle\Controller\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 \Symfony\Bundle\FrameworkBundle\Controller\Response|\Symfony\Component\HttpFoundation\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. if ($data = json_decode($this->get('request')->get('data'), true)) {
  264. $action = $data['action'];
  265. $idx = $data['idx'];
  266. $all_elements = $data['all_elements'];
  267. } else {
  268. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  269. $action = $this->get('request')->get('action');
  270. $idx = $this->get('request')->get('idx');
  271. $all_elements = $this->get('request')->get('all_elements');
  272. $data = $this->get('request')->request->all();
  273. }
  274. $batchActions = $this->admin->getBatchActions();
  275. if (!array_key_exists($action, $batchActions)) {
  276. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  277. }
  278. if (count($idx) == 0 && !$all_elements) { // no item selected
  279. $this->get('session')->setFlash('sonata_flash_info', 'flash_batch_empty');
  280. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  281. }
  282. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  283. if ($askConfirmation) {
  284. if ($this->get('request')->get('confirmation') != 'ok') {
  285. $datagrid = $this->admin->getDatagrid();
  286. $formView = $datagrid->getForm()->createView();
  287. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  288. 'action' => 'list',
  289. 'datagrid' => $datagrid,
  290. 'form' => $formView,
  291. 'data' => json_encode($data),
  292. ));
  293. } else {
  294. $this->get('request')->request->replace($data);
  295. }
  296. }
  297. // execute the action, batchActionXxxxx
  298. $action = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  299. $final_action = sprintf('batchAction%s', ucfirst($action));
  300. if (!method_exists($this, $final_action)) {
  301. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  302. }
  303. $datagrid = $this->admin->getDatagrid();
  304. $datagrid->buildPager();
  305. $query = $datagrid->getQuery();
  306. $query->setFirstResult(null);
  307. $query->setMaxResults(null);
  308. if (count($idx) > 0) {
  309. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  310. }
  311. return call_user_func(array($this, $final_action), $query);
  312. }
  313. /**
  314. * return the Response object associated to the create action
  315. *
  316. * @return \Symfony\Component\HttpFoundation\Response
  317. */
  318. public function createAction()
  319. {
  320. if (false === $this->admin->isGranted('CREATE')) {
  321. throw new AccessDeniedException();
  322. }
  323. $object = $this->admin->getNewInstance();
  324. $this->admin->setSubject($object);
  325. $form = $this->admin->getForm();
  326. $form->setData($object);
  327. if ($this->get('request')->getMethod() == 'POST') {
  328. $form->bindRequest($this->get('request'));
  329. if ($form->isValid()) {
  330. $this->admin->create($object);
  331. if ($this->isXmlHttpRequest()) {
  332. return $this->renderJson(array(
  333. 'result' => 'ok',
  334. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  335. ));
  336. }
  337. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  338. // redirect to edit mode
  339. return $this->redirectTo($object);
  340. }
  341. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  342. }
  343. $view = $form->createView();
  344. // set the theme for the current Admin Form
  345. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  346. return $this->render($this->admin->getEditTemplate(), array(
  347. 'action' => 'create',
  348. 'form' => $view,
  349. 'object' => $object,
  350. ));
  351. }
  352. /**
  353. * return the Response object associated to the view action
  354. *
  355. * @return \Symfony\Component\HttpFoundation\Response
  356. */
  357. public function showAction($id = null)
  358. {
  359. $id = $this->get('request')->get($this->admin->getIdParameter());
  360. $object = $this->admin->getObject($id);
  361. if (!$object) {
  362. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  363. }
  364. if (false === $this->admin->isGranted('VIEW', $object)) {
  365. throw new AccessDeniedException();
  366. }
  367. $this->admin->setSubject($object);
  368. return $this->render($this->admin->getShowTemplate(), array(
  369. 'action' => 'show',
  370. 'object' => $object,
  371. 'elements' => $this->admin->getShow(),
  372. ));
  373. }
  374. /**
  375. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  376. * @param mixed $id
  377. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
  378. */
  379. public function historyAction($id = null)
  380. {
  381. if (false === $this->admin->isGranted('EDIT')) {
  382. throw new AccessDeniedException();
  383. }
  384. $id = $this->get('request')->get($this->admin->getIdParameter());
  385. $object = $this->admin->getObject($id);
  386. if (!$object) {
  387. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  388. }
  389. $manager = $this->get('sonata.admin.audit.manager');
  390. if (!$manager->hasReader($this->admin->getClass())) {
  391. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  392. }
  393. $reader = $manager->getReader($this->admin->getClass());
  394. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  395. return $this->render($this->admin->getTemplate('history'), array(
  396. 'action' => 'history',
  397. 'object' => $object,
  398. 'revisions' => $revisions,
  399. ));
  400. }
  401. /**
  402. * @param null $id
  403. * @param $revision
  404. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
  405. */
  406. public function historyViewRevisionAction($id = null, $revision = null)
  407. {
  408. if (false === $this->admin->isGranted('EDIT')) {
  409. throw new AccessDeniedException();
  410. }
  411. $id = $this->get('request')->get($this->admin->getIdParameter());
  412. $object = $this->admin->getObject($id);
  413. if (!$object) {
  414. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  415. }
  416. $manager = $this->get('sonata.admin.audit.manager');
  417. if (!$manager->hasReader($this->admin->getClass())) {
  418. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  419. }
  420. $reader = $manager->getReader($this->admin->getClass());
  421. // retrieve the revisioned object
  422. $object = $reader->find($this->admin->getClass(), $id, $revision);
  423. if (!$object) {
  424. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  425. }
  426. $this->admin->setSubject($object);
  427. return $this->render($this->admin->getShowTemplate(), array(
  428. 'action' => 'show',
  429. 'object' => $object,
  430. 'elements' => $this->admin->getShow(),
  431. ));
  432. }
  433. /**
  434. * @param \Symfony\Component\HttpFoundation\Request $request
  435. * @return \Symfony\Component\HttpFoundation\Response
  436. */
  437. public function exportAction(Request $request)
  438. {
  439. $format = $request->get('format');
  440. $allowedExportFormats = (array) $this->admin->getExportFormats();
  441. if(!in_array($format, $allowedExportFormats) ) {
  442. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  443. }
  444. $filename = sprintf('export_%s_%s.%s',
  445. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  446. date('Y_m_d_H_i_s', strtotime('now')),
  447. $format
  448. );
  449. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  450. }
  451. }