CRUDController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. * return the Response object associated to the list action
  100. *
  101. * @return Response
  102. */
  103. public function listAction()
  104. {
  105. if ($this->admin->isGranted('LIST')) {
  106. throw new AccessDeniedException();
  107. }
  108. return $this->render($this->admin->getListTemplate(), array(
  109. 'action' => 'list',
  110. 'admin' => $this->admin,
  111. 'base_template' => $this->getBaseTemplate(),
  112. ));
  113. }
  114. /**
  115. * execute a batch delete
  116. *
  117. * @param array $idx
  118. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  119. */
  120. public function batchActionDelete($idx)
  121. {
  122. if ($this->admin->isGranted('DELETE')) {
  123. throw new AccessDeniedException();
  124. }
  125. $modelManager = $this->admin->getModelManager();
  126. $modelManager->batchDelete($this->admin->getClass(), $idx);
  127. // todo : add confirmation flash var
  128. return new RedirectResponse($this->admin->generateUrl('list'));
  129. }
  130. public function deleteAction($id)
  131. {
  132. if ($this->admin->isGranted('DELETE')) {
  133. throw new AccessDeniedException();
  134. }
  135. $id = $this->get('request')->get($this->admin->getIdParameter());
  136. $object = $this->admin->getObject($id);
  137. if (!$object) {
  138. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  139. }
  140. $this->admin->delete($object);
  141. return new RedirectResponse($this->admin->generateUrl('list'));
  142. }
  143. /**
  144. * return the Response object associated to the edit action
  145. *
  146. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  147. * @param $id
  148. * @return \Symfony\Component\HttpFoundation\Response
  149. */
  150. public function editAction($id)
  151. {
  152. if ($this->admin->isGranted('EDIT')) {
  153. throw new AccessDeniedException();
  154. }
  155. $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));
  156. if (!$object) {
  157. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  158. }
  159. $this->admin->setSubject($object);
  160. $form = $this->admin->getForm($object);
  161. if ($this->get('request')->getMethod() == 'POST') {
  162. $form->bindRequest($this->get('request'));
  163. if ($form->isValid()) {
  164. $this->admin->update($object);
  165. if ($this->isXmlHttpRequest()) {
  166. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  167. }
  168. // redirect to edit mode
  169. return $this->redirectTo($object);
  170. }
  171. }
  172. return $this->render($this->admin->getEditTemplate(), array(
  173. 'action' => 'edit',
  174. 'form' => $form->createView(),
  175. 'object' => $object,
  176. 'admin' => $this->admin,
  177. 'base_template' => $this->getBaseTemplate(),
  178. ));
  179. }
  180. /**
  181. * redirect the user depend on this choice
  182. *
  183. * @param $object
  184. * @return \Symfony\Component\HttpFoundation\Response
  185. */
  186. public function redirectTo($object)
  187. {
  188. $url = false;
  189. if ($this->get('request')->get('btn_update_and_list')) {
  190. $url = $this->admin->generateUrl('list');
  191. }
  192. if ($this->get('request')->get('btn_create_and_create')) {
  193. $url = $this->admin->generateUrl('create');
  194. }
  195. if (!$url) {
  196. $url = $this->admin->generateUrl('edit', array('id' => $object->getId()));
  197. }
  198. return new RedirectResponse($url);
  199. }
  200. /**
  201. * return the Response object associated to the batch action
  202. *
  203. * @throws \RuntimeException
  204. * @return \Symfony\Component\HttpFoundation\Response
  205. */
  206. public function batchAction()
  207. {
  208. if ($this->get('request')->getMethod() != 'POST') {
  209. throw new \RuntimeException('invalid request type, POST expected');
  210. }
  211. $action = $this->get('request')->get('action');
  212. $idx = $this->get('request')->get('idx');
  213. if (count($idx) == 0) { // no item selected
  214. // todo : add flash information
  215. return new RedirectResponse($this->admin->generateUrl('list'));
  216. }
  217. // execute the action, batchActionXxxxx
  218. $final_action = sprintf('batchAction%s', ucfirst($action));
  219. if (!method_exists($this, $final_action)) {
  220. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  221. }
  222. return call_user_func(array($this, $final_action), $idx);
  223. }
  224. /**
  225. * return the Response object associated to the create action
  226. *
  227. * @return \Symfony\Component\HttpFoundation\Response
  228. */
  229. public function createAction()
  230. {
  231. if ($this->admin->isGranted('CREATE')) {
  232. throw new AccessDeniedException();
  233. }
  234. $object = $this->admin->getNewInstance();
  235. $form = $this->admin->getForm($object);
  236. $this->admin->setSubject($object);
  237. if ($this->get('request')->getMethod() == 'POST') {
  238. $form->bindRequest($this->get('request'));
  239. if ($form->isValid()) {
  240. $this->admin->create($object);
  241. if ($this->isXmlHttpRequest()) {
  242. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  243. }
  244. // redirect to edit mode
  245. return $this->redirectTo($object);
  246. }
  247. }
  248. return $this->render($this->admin->getEditTemplate(), array(
  249. 'action' => 'create',
  250. 'form' => $form->createView(),
  251. 'admin' => $this->admin,
  252. 'object' => $object,
  253. 'base_template' => $this->getBaseTemplate(),
  254. ));
  255. }
  256. }