CRUDController.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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\DependencyInjection\ContainerInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  16. class CRUDController extends Controller
  17. {
  18. /**
  19. * The related Admin class
  20. *
  21. * @var \Sonata\AdminBundle\Admin\AdminInterface
  22. */
  23. protected $admin;
  24. /**
  25. * @param mixed $data
  26. * @param integer $status
  27. * @param array $headers
  28. *
  29. * @return Response with json encoded data
  30. */
  31. public function renderJson($data, $status = 200, $headers = array())
  32. {
  33. // fake content-type so browser does not show the download popup when this
  34. // response is rendered through an iframe (used by the jquery.form.js plugin)
  35. // => don't know yet if it is the best solution
  36. if ($this->get('request')->get('_xml_http_request')
  37. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  38. $headers['Content-Type'] = 'text/plain';
  39. } else {
  40. $headers['Content-Type'] = 'application/json';
  41. }
  42. return new Response(json_encode($data), $status, $headers);
  43. }
  44. /**
  45. *
  46. * @return boolean true if the request is done by an ajax like query
  47. */
  48. public function isXmlHttpRequest()
  49. {
  50. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  51. }
  52. /**
  53. * Sets the Container associated with this Controller.
  54. *
  55. * @param ContainerInterface $container A ContainerInterface instance
  56. */
  57. public function setContainer(ContainerInterface $container = null)
  58. {
  59. $this->container = $container;
  60. $this->configure();
  61. }
  62. /**
  63. * Contextualize the admin class depends on the current request
  64. *
  65. * @throws \RuntimeException
  66. * @return void
  67. */
  68. public function configure()
  69. {
  70. $adminCode = $this->container->get('request')->get('_sonata_admin');
  71. if (!$adminCode) {
  72. 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')));
  73. }
  74. $this->admin = $this->container->get('sonata_admin.admin.pool')->getAdminByAdminCode($adminCode);
  75. if (!$this->admin) {
  76. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  77. }
  78. $rootAdmin = $this->admin;
  79. if ($this->admin->isChild()) {
  80. $this->admin->setCurrentChild(true);
  81. $rootAdmin = $rootAdmin->getParent();
  82. }
  83. $rootAdmin->setRequest($this->container->get('request'));
  84. }
  85. /**
  86. * return the base template name
  87. *
  88. * @return string the template name
  89. */
  90. public function getBaseTemplate()
  91. {
  92. if ($this->isXmlHttpRequest()) {
  93. return $this->container->getParameter('sonata_admin.templates.ajax');
  94. }
  95. return $this->container->getParameter('sonata_admin.templates.layout');
  96. }
  97. /**
  98. * return the Response object associated to the list action
  99. *
  100. * @return Response
  101. */
  102. public function listAction()
  103. {
  104. return $this->render($this->admin->getListTemplate(), array(
  105. 'action' => 'list',
  106. 'admin' => $this->admin,
  107. 'base_template' => $this->getBaseTemplate(),
  108. ));
  109. }
  110. /**
  111. * execute a batch delete
  112. *
  113. * @param array $idx
  114. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  115. */
  116. public function batchActionDelete($idx)
  117. {
  118. $modelManager = $this->admin->getModelManager();
  119. $modelManager->batchDelete($this->admin->getClass(), $idx);
  120. // todo : add confirmation flash var
  121. return new RedirectResponse($this->admin->generateUrl('list'));
  122. }
  123. public function deleteAction($id)
  124. {
  125. $id = $this->get('request')->get($this->admin->getIdParameter());
  126. $object = $this->admin->getObject($id);
  127. if (!$object) {
  128. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  129. }
  130. $this->admin->delete($object);
  131. return new RedirectResponse($this->admin->generateUrl('list'));
  132. }
  133. /**
  134. * return the Response object associated to the edit action
  135. *
  136. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  137. * @param $id
  138. * @return \Symfony\Component\HttpFoundation\Response
  139. */
  140. public function editAction($id)
  141. {
  142. $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));
  143. if (!$object) {
  144. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  145. }
  146. $this->admin->setSubject($object);
  147. $form = $this->admin->getForm($object);
  148. if ($this->get('request')->getMethod() == 'POST') {
  149. $form->bind($this->get('request'));
  150. if ($form->isValid()) {
  151. $this->admin->update($object);
  152. if ($this->isXmlHttpRequest()) {
  153. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  154. }
  155. // redirect to edit mode
  156. return $this->redirectTo($object);
  157. }
  158. }
  159. return $this->render($this->admin->getEditTemplate(), array(
  160. 'action' => 'edit',
  161. 'form' => $form,
  162. 'admin' => $this->admin,
  163. 'base_template' => $this->getBaseTemplate(),
  164. ));
  165. }
  166. /**
  167. * redirect the user depend on this choice
  168. *
  169. * @param $object
  170. * @return \Symfony\Component\HttpFoundation\Response
  171. */
  172. public function redirectTo($object) {
  173. $url = false;
  174. if ($this->get('request')->get('btn_update_and_list')) {
  175. $url = $this->admin->generateUrl('list');
  176. }
  177. if ($this->get('request')->get('btn_create_and_create')) {
  178. $url = $this->admin->generateUrl('create');
  179. }
  180. if (!$url) {
  181. $url = $this->admin->generateUrl('edit', array('id' => $object->getId()));
  182. }
  183. return new RedirectResponse($url);
  184. }
  185. /**
  186. * return the Response object associated to the batch action
  187. *
  188. * @throws \RuntimeException
  189. * @return \Symfony\Component\HttpFoundation\Response
  190. */
  191. public function batchAction()
  192. {
  193. if ($this->get('request')->getMethod() != 'POST') {
  194. throw new \RuntimeException('invalid request type, POST expected');
  195. }
  196. $action = $this->get('request')->get('action');
  197. $idx = $this->get('request')->get('idx');
  198. if (count($idx) == 0) { // no item selected
  199. // todo : add flash information
  200. return new RedirectResponse($this->admin->generateUrl('list'));
  201. }
  202. // execute the action, batchActionXxxxx
  203. $final_action = sprintf('batchAction%s', ucfirst($action));
  204. if (!method_exists($this, $final_action)) {
  205. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  206. }
  207. return call_user_func(array($this, $final_action), $idx);
  208. }
  209. /**
  210. * return the Response object associated to the create action
  211. *
  212. * @return \Symfony\Component\HttpFoundation\Response
  213. */
  214. public function createAction()
  215. {
  216. $object = $this->admin->getNewInstance();
  217. $form = $this->admin->getForm($object);
  218. $this->admin->setSubject($object);
  219. if ($this->get('request')->getMethod() == 'POST') {
  220. $form->bind($this->get('request'));
  221. if ($form->isValid()) {
  222. $this->admin->create($object);
  223. if ($this->isXmlHttpRequest()) {
  224. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  225. }
  226. // redirect to edit mode
  227. return $this->redirectTo($object);
  228. }
  229. }
  230. return $this->render($this->admin->getEditTemplate(), array(
  231. 'action' => 'create',
  232. 'form' => $form,
  233. 'admin' => $this->admin,
  234. 'base_template' => $this->getBaseTemplate(),
  235. ));
  236. }
  237. }