CRUDController.php 11 KB

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