CRUDController.php 15 KB

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