CRUDController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. class CRUDController extends Controller
  18. {
  19. /**
  20. * The related Admin class
  21. *
  22. * @var \Sonata\AdminBundle\Admin\AdminInterface
  23. */
  24. protected $admin;
  25. /**
  26. * @param mixed $data
  27. * @param integer $status
  28. * @param array $headers
  29. *
  30. * @return Response with json encoded data
  31. */
  32. public function renderJson($data, $status = 200, $headers = array())
  33. {
  34. // fake content-type so browser does not show the download popup when this
  35. // response is rendered through an iframe (used by the jquery.form.js plugin)
  36. // => don't know yet if it is the best solution
  37. if ($this->get('request')->get('_xml_http_request')
  38. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  39. $headers['Content-Type'] = 'text/plain';
  40. } else {
  41. $headers['Content-Type'] = 'application/json';
  42. }
  43. return new Response(json_encode($data), $status, $headers);
  44. }
  45. /**
  46. *
  47. * @return boolean true if the request is done by an ajax like query
  48. */
  49. public function isXmlHttpRequest()
  50. {
  51. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  52. }
  53. /**
  54. * Sets the Container associated with this Controller.
  55. *
  56. * @param ContainerInterface $container A ContainerInterface instance
  57. */
  58. public function setContainer(ContainerInterface $container = null)
  59. {
  60. $this->container = $container;
  61. $this->configure();
  62. }
  63. /**
  64. * Contextualize the admin class depends on the current request
  65. *
  66. * @throws \RuntimeException
  67. * @return void
  68. */
  69. public function configure()
  70. {
  71. $adminCode = $this->container->get('request')->get('_sonata_admin');
  72. if (!$adminCode) {
  73. 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')));
  74. }
  75. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  76. if (!$this->admin) {
  77. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  78. }
  79. $rootAdmin = $this->admin;
  80. if ($this->admin->isChild()) {
  81. $this->admin->setCurrentChild(true);
  82. $rootAdmin = $rootAdmin->getParent();
  83. }
  84. $rootAdmin->setRequest($this->container->get('request'));
  85. }
  86. /**
  87. * return the base template name
  88. *
  89. * @return string the template name
  90. */
  91. public function getBaseTemplate()
  92. {
  93. if ($this->isXmlHttpRequest()) {
  94. return $this->container->getParameter('sonata.admin.templates.ajax');
  95. }
  96. return $this->container->getParameter('sonata.admin.templates.layout');
  97. }
  98. /**
  99. * @param $view
  100. * @param array $parameters
  101. * @param null|\Symfony\Component\HttpFoundation\Response $response
  102. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
  103. */
  104. public function render($view, array $parameters = array(), Response $response = null)
  105. {
  106. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  107. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  108. return parent::render($view, $parameters);
  109. }
  110. /**
  111. * return the Response object associated to the list action
  112. *
  113. * @return Response
  114. */
  115. public function listAction()
  116. {
  117. if (false === $this->admin->isGranted('LIST')) {
  118. throw new AccessDeniedException();
  119. }
  120. $datagrid = $this->admin->getDatagrid();
  121. $formView = $datagrid->getForm()->createView();
  122. // set the theme for the current Admin Form
  123. $this->get('twig')->getExtension('form')->setTheme($formView, $this->admin->getFilterTheme());
  124. return $this->render($this->admin->getListTemplate(), array(
  125. 'action' => 'list',
  126. 'form' => $formView,
  127. 'datagrid' => $datagrid
  128. ));
  129. }
  130. /**
  131. * execute a batch delete
  132. *
  133. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  134. * @param $query
  135. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  136. */
  137. public function batchActionDelete($query)
  138. {
  139. if (false === $this->admin->isGranted('DELETE')) {
  140. throw new AccessDeniedException();
  141. }
  142. $modelManager = $this->admin->getModelManager();
  143. try {
  144. $modelManager->batchDelete($this->admin->getClass(), $query);
  145. $this->get('session')->setFlash('sonata_flash_success', 'flash_batch_delete_success');
  146. } catch ( \PDOException $e ) {
  147. $this->get('session')->setFlash('sonata_flash_error', 'flash_batch_delete_error');
  148. }
  149. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  150. }
  151. /**
  152. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  153. * @param $id
  154. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response|\Symfony\Component\HttpFoundation\RedirectResponse
  155. */
  156. public function deleteAction($id)
  157. {
  158. if (false === $this->admin->isGranted('DELETE')) {
  159. throw new AccessDeniedException();
  160. }
  161. $id = $this->get('request')->get($this->admin->getIdParameter());
  162. $object = $this->admin->getObject($id);
  163. if (!$object) {
  164. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  165. }
  166. if ($this->getRequest()->getMethod() == 'DELETE') {
  167. try {
  168. $this->admin->delete($object);
  169. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  170. } catch ( \PDOException $e ) {
  171. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  172. }
  173. return new RedirectResponse($this->admin->generateUrl('list'));
  174. }
  175. return $this->render('SonataAdminBundle:CRUD:delete.html.twig', array(
  176. 'object' => $object,
  177. 'action' => 'delete'
  178. ));
  179. }
  180. /**
  181. * return the Response object associated to the edit action
  182. *
  183. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  184. * @param $id
  185. * @return \Symfony\Component\HttpFoundation\Response
  186. */
  187. public function editAction($id)
  188. {
  189. if (false === $this->admin->isGranted('EDIT')) {
  190. throw new AccessDeniedException();
  191. }
  192. $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));
  193. if (!$object) {
  194. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  195. }
  196. $this->admin->setSubject($object);
  197. $form = $this->admin->getForm();
  198. $form->setData($object);
  199. if ($this->get('request')->getMethod() == 'POST') {
  200. $form->bindRequest($this->get('request'));
  201. if ($form->isValid()) {
  202. $this->admin->update($object);
  203. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  204. if ($this->isXmlHttpRequest()) {
  205. return $this->renderJson(array(
  206. 'result' => 'ok',
  207. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  208. ));
  209. }
  210. // redirect to edit mode
  211. return $this->redirectTo($object);
  212. }
  213. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  214. }
  215. $view = $form->createView();
  216. // set the theme for the current Admin Form
  217. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  218. return $this->render($this->admin->getEditTemplate(), array(
  219. 'action' => 'edit',
  220. 'form' => $view,
  221. 'object' => $object,
  222. ));
  223. }
  224. /**
  225. * redirect the user depend on this choice
  226. *
  227. * @param $object
  228. * @return \Symfony\Component\HttpFoundation\Response
  229. */
  230. public function redirectTo($object)
  231. {
  232. $url = false;
  233. if ($this->get('request')->get('btn_update_and_list')) {
  234. $url = $this->admin->generateUrl('list');
  235. }
  236. if ($this->get('request')->get('btn_create_and_create')) {
  237. $url = $this->admin->generateUrl('create');
  238. }
  239. if (!$url) {
  240. $url = $this->admin->generateObjectUrl('edit', $object);
  241. }
  242. return new RedirectResponse($url);
  243. }
  244. /**
  245. * return the Response object associated to the batch action
  246. *
  247. * @throws \RuntimeException
  248. * @return \Symfony\Component\HttpFoundation\Response
  249. */
  250. public function batchAction()
  251. {
  252. if ($this->get('request')->getMethod() != 'POST') {
  253. throw new \RuntimeException('invalid request type, POST expected');
  254. }
  255. if ($data = json_decode($this->get('request')->get('data'), true)) {
  256. $action = $data['action'];
  257. $idx = $data['idx'];
  258. $all_elements = $data['all_elements'];
  259. } else {
  260. $action = $this->get('request')->get('action');
  261. $idx = $this->get('request')->get('idx');
  262. $all_elements = $this->get('request')->get('all_elements', false);
  263. }
  264. $batchActions = $this->admin->getBatchActions();
  265. if (!array_key_exists($action, $batchActions)) {
  266. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  267. }
  268. if (count($idx) == 0 && !$all_elements) { // no item selected
  269. $this->get('session')->setFlash('sonata_flash_notice', 'flash_batch_empty');
  270. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  271. }
  272. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  273. if ($askConfirmation && $this->get('request')->get('confirmation') != 'ok') {
  274. $data = json_encode(array(
  275. 'action' => $action,
  276. 'idx' => $idx,
  277. 'all_elements' => $all_elements,
  278. ));
  279. $datagrid = $this->admin->getDatagrid();
  280. $formView = $datagrid->getForm()->createView();
  281. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  282. 'action' => 'list',
  283. 'datagrid' => $datagrid,
  284. 'form' => $formView,
  285. 'data' => $data,
  286. ));
  287. }
  288. // execute the action, batchActionXxxxx
  289. $action = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  290. $final_action = sprintf('batchAction%s', ucfirst($action));
  291. if (!method_exists($this, $final_action)) {
  292. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  293. }
  294. $datagrid = $this->admin->getDatagrid();
  295. $datagrid->buildPager();
  296. $query = $datagrid->getQuery();
  297. $query->setFirstResult(null);
  298. $query->setMaxResults(null);
  299. if (count($idx) > 0) {
  300. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  301. }
  302. return call_user_func(array($this, $final_action), $query);
  303. }
  304. /**
  305. * return the Response object associated to the create action
  306. *
  307. * @return \Symfony\Component\HttpFoundation\Response
  308. */
  309. public function createAction()
  310. {
  311. if (false === $this->admin->isGranted('CREATE')) {
  312. throw new AccessDeniedException();
  313. }
  314. $object = $this->admin->getNewInstance();
  315. $this->admin->setSubject($object);
  316. $form = $this->admin->getForm();
  317. $form->setData($object);
  318. if ($this->get('request')->getMethod() == 'POST') {
  319. $form->bindRequest($this->get('request'));
  320. if ($form->isValid()) {
  321. $this->admin->create($object);
  322. if ($this->isXmlHttpRequest()) {
  323. return $this->renderJson(array(
  324. 'result' => 'ok',
  325. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  326. ));
  327. }
  328. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  329. // redirect to edit mode
  330. return $this->redirectTo($object);
  331. }
  332. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  333. }
  334. $view = $form->createView();
  335. // set the theme for the current Admin Form
  336. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  337. return $this->render($this->admin->getEditTemplate(), array(
  338. 'action' => 'create',
  339. 'form' => $view,
  340. 'object' => $object,
  341. ));
  342. }
  343. /**
  344. * return the Response object associated to the view action
  345. *
  346. * @return \Symfony\Component\HttpFoundation\Response
  347. */
  348. public function showAction($id)
  349. {
  350. if (false === $this->admin->isGranted('SHOW')) {
  351. throw new AccessDeniedException();
  352. }
  353. $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));
  354. if (!$object) {
  355. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  356. }
  357. $this->admin->setSubject($object);
  358. // build the show list
  359. $elements = $this->admin->getShow();
  360. return $this->render($this->admin->getShowTemplate(), array(
  361. 'action' => 'show',
  362. 'object' => $object,
  363. 'elements' => $this->admin->getShow(),
  364. ));
  365. }
  366. }