CRUDController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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\Component\Form\Form;
  16. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  17. class CRUDController extends Controller
  18. {
  19. /**
  20. * The related Admin class
  21. *
  22. * @var Admin
  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.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. $this->admin->setRequest($this->container->get('request'));
  80. if ($this->admin->isChild()) {
  81. $this->admin->setCurrentChild(true);
  82. }
  83. }
  84. /**
  85. * return the base template name
  86. *
  87. * @return string the template name
  88. */
  89. public function getBaseTemplate()
  90. {
  91. if ($this->isXmlHttpRequest()) {
  92. return $this->container->getParameter('sonata_admin.templates.ajax');
  93. }
  94. return $this->container->getParameter('sonata_admin.templates.layout');
  95. }
  96. /**
  97. * return the Response object associated to the list action
  98. *
  99. * @return Response
  100. */
  101. public function listAction()
  102. {
  103. $datagrid = $this->admin->getDatagrid();
  104. return $this->render($this->admin->getListTemplate(), array(
  105. 'datagrid' => $datagrid,
  106. 'list' => $this->admin->getList(),
  107. 'admin' => $this->admin,
  108. 'base_template' => $this->getBaseTemplate(),
  109. 'side_menu' => $this->getSideMenu('list'),
  110. 'breadcrumbs' => $this->getBreadcrumbs('list'),
  111. ));
  112. }
  113. /**
  114. * execute a batch delete
  115. *
  116. * @param array $idx
  117. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  118. */
  119. public function batchActionDelete($idx)
  120. {
  121. $em = $this->admin->getModelManager();
  122. $query_builder = $em->createQueryBuilder();
  123. $objects = $query_builder
  124. ->select('o')
  125. ->from($this->admin->getClass(), 'o')
  126. ->add('where', $query_builder->expr()->in('o.id', $idx))
  127. ->getQuery()
  128. ->execute();
  129. foreach ($objects as $object) {
  130. $em->remove($object);
  131. }
  132. $em->flush();
  133. // todo : add confirmation flash var
  134. return new RedirectResponse($this->admin->generateUrl('list'));
  135. }
  136. public function deleteAction($id)
  137. {
  138. $id = $this->get('request')->get($this->admin->getIdParameter());
  139. $object = $this->admin->getObject($id);
  140. if (!$object) {
  141. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  142. }
  143. $em = $this->admin->getModelManager();
  144. $em->remove($object);
  145. $em->flush();
  146. return new RedirectResponse($this->admin->generateUrl('list'));
  147. }
  148. /**
  149. * return the Response object associated to the edit action
  150. *
  151. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  152. * @param $id
  153. * @return \Symfony\Component\HttpFoundation\Response
  154. */
  155. public function editAction($id)
  156. {
  157. $object = $this->admin->getObject($this->get('request')->get($this->admin->getIdParameter()));
  158. if (!$object) {
  159. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  160. }
  161. $this->admin->setSubject($object);
  162. $form = $this->admin->getForm($object);
  163. if ($this->get('request')->getMethod() == 'POST') {
  164. $form->bind($this->get('request'));
  165. if ($form->isValid()) {
  166. $this->admin->preUpdate($object);
  167. $this->admin->getModelManager()->persist($object);
  168. $this->admin->getModelManager()->flush($object);
  169. $this->admin->postUpdate($object);
  170. if ($this->isXmlHttpRequest()) {
  171. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  172. }
  173. // redirect to edit mode
  174. return $this->redirectTo($object);
  175. }
  176. }
  177. return $this->render($this->admin->getEditTemplate(), array(
  178. 'form' => $form,
  179. 'object' => $object,
  180. 'fields' => $this->admin->getFormFieldDescriptions(),
  181. 'form_groups' => $this->admin->getFormGroups(),
  182. 'admin' => $this->admin,
  183. 'base_template' => $this->getBaseTemplate(),
  184. 'side_menu' => $this->getSideMenu('edit'),
  185. 'breadcrumbs' => $this->getBreadcrumbs('edit'),
  186. ));
  187. }
  188. /**
  189. * redirect the user depend on this choice
  190. *
  191. * @param $object
  192. * @return \Symfony\Component\HttpFoundation\Response
  193. */
  194. public function redirectTo($object) {
  195. $url = false;
  196. if ($this->get('request')->get('btn_update_and_list')) {
  197. $url = $this->admin->generateUrl('list');
  198. }
  199. if ($this->get('request')->get('btn_create_and_create')) {
  200. $url = $this->admin->generateUrl('create');
  201. }
  202. if (!$url) {
  203. $url = $this->admin->generateUrl('edit', array('id' => $object->getId()));
  204. }
  205. return new RedirectResponse($url);
  206. }
  207. /**
  208. * return the Response object associated to the batch action
  209. *
  210. * @throws \RuntimeException
  211. * @return \Symfony\Component\HttpFoundation\Response
  212. */
  213. public function batchAction()
  214. {
  215. if ($this->get('request')->getMethod() != 'POST') {
  216. throw new \RuntimeException('invalid request type, POST expected');
  217. }
  218. $action = $this->get('request')->get('action');
  219. $idx = $this->get('request')->get('idx');
  220. if (count($idx) == 0) { // no item selected
  221. // todo : add flash information
  222. return new RedirectResponse($this->admin->generateUrl('list'));
  223. }
  224. // execute the action, batchActionXxxxx
  225. $final_action = sprintf('batchAction%s', ucfirst($action));
  226. if (!method_exists($this, $final_action)) {
  227. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  228. }
  229. return call_user_func(array($this, $final_action), $idx);
  230. }
  231. /**
  232. * return the Response object associated to the create action
  233. *
  234. * @return \Symfony\Component\HttpFoundation\Response
  235. */
  236. public function createAction()
  237. {
  238. $object = $this->admin->getNewInstance();
  239. $form = $this->admin->getForm($object);
  240. $this->admin->setSubject($object);
  241. if ($this->get('request')->getMethod() == 'POST') {
  242. $form->bind($this->get('request'));
  243. if ($form->isValid()) {
  244. $this->admin->prePersist($object);
  245. $this->admin->getModelManager()->persist($object);
  246. $this->admin->getModelManager()->flush($object);
  247. $this->admin->postPersist($object);
  248. if ($this->isXmlHttpRequest()) {
  249. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  250. }
  251. // redirect to edit mode
  252. return $this->redirectTo($object);
  253. }
  254. }
  255. return $this->render($this->admin->getEditTemplate(), array(
  256. 'form' => $form,
  257. 'object' => $object,
  258. 'fields' => $this->admin->getFormFieldDescriptions(),
  259. 'form_groups' => $this->admin->getFormGroups(),
  260. 'admin' => $this->admin,
  261. 'base_template' => $this->getBaseTemplate(),
  262. 'side_menu' => $this->getSideMenu('create'),
  263. 'breadcrumbs' => $this->getBreadcrumbs('create'),
  264. ));
  265. }
  266. /**
  267. * @param string $action
  268. * @return Knplabs\MenuBundle\Menu
  269. */
  270. public function getSideMenu($action)
  271. {
  272. if ($this->admin->isChild()) {
  273. return $this->admin->getParent()->getSideMenu($action, $this->admin);
  274. }
  275. return $this->admin->getSideMenu($action);
  276. }
  277. /**
  278. * @param string $action
  279. * @return array
  280. */
  281. public function getBreadcrumbs($action)
  282. {
  283. if ($this->admin->isChild()) {
  284. return $this->admin->getParent()->getBreadcrumbs($action);
  285. }
  286. return $this->admin->getBreadcrumbs($action);
  287. }
  288. }