CRUDController.php 11 KB

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