CRUDController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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\BaseApplicationBundle\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. *
  28. * @return Response with json encoded data
  29. */
  30. public function renderJson($data, $status = 200, $headers = array())
  31. {
  32. // fake content-type so browser does not show the download popup when this
  33. // response is rendered through an iframe (used by the jquery.form.js plugin)
  34. // => don't know yet if it is the best solution
  35. if($this->get('request')->get('_xml_http_request')) {
  36. $headers['Content-Type'] = 'text/plain';
  37. } else {
  38. $headers['Content-Type'] = 'application/json';
  39. }
  40. return new Response(json_encode($data), $status, $headers);
  41. }
  42. /**
  43. *
  44. * @return boolean true if the request is done by an ajax like query
  45. */
  46. public function isXmlHttpRequest()
  47. {
  48. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  49. }
  50. /**
  51. * Sets the Container associated with this Controller.
  52. *
  53. * @param ContainerInterface $container A ContainerInterface instance
  54. */
  55. public function setContainer(ContainerInterface $container = null)
  56. {
  57. $this->container = $container;
  58. $this->configure();
  59. }
  60. public function configure()
  61. {
  62. $actionName = $this->container->get('request')->get('_bab_action');
  63. $this->admin = $this->container
  64. ->get('sonata_base_application.admin.pool')
  65. ->getAdminByActionName($actionName);
  66. if(!$this->admin) {
  67. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  68. }
  69. if($this->container->get('request')->get('uniqid')) {
  70. $this->admin->setUniqid($this->container->get('request')->get('uniqid'));
  71. }
  72. if($this->admin->isChild()) {
  73. $this->admin->setCurrentChild(true);
  74. }
  75. }
  76. /**
  77. * return the base template name
  78. *
  79. * @return string the template name
  80. */
  81. public function getBaseTemplate()
  82. {
  83. if ($this->isXmlHttpRequest()) {
  84. return $this->container->getParameter('sonata_base_application.templates.ajax');
  85. }
  86. return $this->container->getParameter('sonata_base_application.templates.layout');
  87. }
  88. /**
  89. * return the Response object associated to the list action
  90. *
  91. * @return Response
  92. */
  93. public function listAction()
  94. {
  95. $datagrid = $this->admin->getDatagrid();
  96. return $this->render($this->admin->getListTemplate(), array(
  97. 'datagrid' => $datagrid,
  98. 'list' => $this->admin->getList(),
  99. 'admin' => $this->admin,
  100. 'base_template' => $this->getBaseTemplate(),
  101. 'side_menu' => $this->getSideMenu('list'),
  102. 'breadcrumbs' => $this->getBreadcrumbs('list'),
  103. ));
  104. }
  105. public function batchActionDelete($idx)
  106. {
  107. $em = $this->admin->getEntityManager();
  108. $query_builder = $em->createQueryBuilder();
  109. $objects = $query_builder
  110. ->select('o')
  111. ->from($this->admin->getClass(), 'o')
  112. ->add('where', $query_builder->expr()->in('o.id', $idx))
  113. ->getQuery()
  114. ->execute();
  115. foreach ($objects as $object) {
  116. $em->remove($object);
  117. }
  118. $em->flush();
  119. // todo : add confirmation flash var
  120. return new RedirectResponse($this->admin->generateUrl('list'));
  121. }
  122. public function deleteAction($id)
  123. {
  124. // todo
  125. }
  126. /**
  127. * return the Response object associated to the edit action
  128. *
  129. * @return Response
  130. */
  131. public function editAction($id)
  132. {
  133. $id = $this->get('request')->get($this->admin->getIdParameter());
  134. if ($id instanceof Form) {
  135. $object = $id->getData();
  136. $form = $id;
  137. // todo : refactor the Form Creation
  138. $this->admin->getForm($object);
  139. } else {
  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. $form = $this->admin->getForm($object);
  145. }
  146. $this->admin->setSubject($object);
  147. return $this->render($this->admin->getEditTemplate(), array(
  148. 'form' => $form,
  149. 'object' => $object,
  150. 'fields' => $this->admin->getFormFieldDescriptions(),
  151. 'form_groups' => $this->admin->getFormGroups(),
  152. 'admin' => $this->admin,
  153. 'base_template' => $this->getBaseTemplate(),
  154. 'side_menu' => $this->getSideMenu('edit'),
  155. 'breadcrumbs' => $this->getBreadcrumbs('edit'),
  156. ));
  157. }
  158. /**
  159. * return the Response object associated to the update action
  160. *
  161. * @return Response
  162. */
  163. public function updateAction()
  164. {
  165. if ($this->get('request')->getMethod() != 'POST') {
  166. throw new \RuntimeException('invalid request type, POST expected');
  167. }
  168. $id = $this->get('request')->get($this->admin->getIdParameter());
  169. if (is_numeric($id)) {
  170. $object = $this->admin->getObject($id);
  171. if (!$object) {
  172. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  173. }
  174. $action = 'edit';
  175. } else {
  176. $object = $this->admin->getNewInstance();
  177. $action = 'create';
  178. }
  179. $this->admin->setSubject($object);
  180. $form = $this->admin->getForm($object);
  181. $form->bind($this->get('request'));
  182. if ($form->isValid()) {
  183. if ($action == 'create') {
  184. $this->admin->preInsert($object);
  185. } else {
  186. $this->admin->preUpdate($object);
  187. }
  188. $this->admin->getEntityManager()->persist($object);
  189. $this->admin->getEntityManager()->flush($object);
  190. if ($action == 'create') {
  191. $this->admin->postInsert($object);
  192. } else {
  193. $this->admin->postUpdate($object);
  194. }
  195. if ($this->isXmlHttpRequest()) {
  196. return $this->renderJson(array('result' => 'ok', 'objectId' => $object->getId()));
  197. }
  198. // redirect to edit mode
  199. return $this->redirectTo($object);
  200. }
  201. return $this->forward(sprintf('%s:%s', $this->admin->getBaseControllerName(), $action), array(
  202. 'id' => $form
  203. ));
  204. }
  205. /**
  206. * redirect the user depend on this choice
  207. *
  208. * @param $object
  209. * @return Response
  210. */
  211. public function redirectTo($object) {
  212. $url = false;
  213. if ($this->get('request')->get('btn_update_and_list')) {
  214. $url = $this->admin->generateUrl('list');
  215. }
  216. if ($this->get('request')->get('btn_create_and_create')) {
  217. $url = $this->admin->generateUrl('create');
  218. }
  219. if (!$url) {
  220. $url = $this->admin->generateUrl('edit', array('id' => $object->getId()));
  221. }
  222. return new RedirectResponse($url);
  223. }
  224. /**
  225. * return the Response object associated to the batch action
  226. *
  227. * @throws \RuntimeException
  228. * @return Response
  229. */
  230. public function batchAction()
  231. {
  232. if ($this->get('request')->getMethod() != 'POST') {
  233. throw new \RuntimeException('invalid request type, POST expected');
  234. }
  235. $action = $this->get('request')->get('action');
  236. $idx = $this->get('request')->get('idx');
  237. if (count($idx) == 0) { // no item selected
  238. // todo : add flash information
  239. return new RedirectResponse($this->admin->generateUrl('list'));
  240. }
  241. // execute the action, batchActionXxxxx
  242. $final_action = sprintf('batchAction%s', ucfirst($action));
  243. if (!method_exists($this, $final_action)) {
  244. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  245. }
  246. return call_user_func(array($this, $final_action), $idx);
  247. }
  248. /**
  249. * return the Response object associated to the create action
  250. *
  251. * @return Response
  252. */
  253. public function createAction($id = null)
  254. {
  255. if ($id instanceof Form) {
  256. $object = $id->getData();
  257. $form = $id;
  258. } else {
  259. $object = $this->admin->getNewInstance();
  260. $form = $this->admin->getForm($object);
  261. }
  262. $this->admin->setSubject($object);
  263. return $this->render($this->admin->getEditTemplate(), array(
  264. 'form' => $form,
  265. 'object' => $object,
  266. 'fields' => $this->admin->getFormFieldDescriptions(),
  267. 'form_groups' => $this->admin->getFormGroups(),
  268. 'admin' => $this->admin,
  269. 'base_template' => $this->getBaseTemplate(),
  270. 'side_menu' => $this->getSideMenu('create'),
  271. 'breadcrumbs' => $this->getBreadcrumbs('create'),
  272. ));
  273. }
  274. /**
  275. * @param string $action
  276. * @return Knplabs\MenuBundle\Menu
  277. */
  278. public function getSideMenu($action)
  279. {
  280. if($this->admin->isChild()) {
  281. return $this->admin->getParent()->getSideMenu($action, $this->admin);
  282. }
  283. return $this->admin->getSideMenu($action);
  284. }
  285. /**
  286. * @param string $action
  287. * @return array
  288. */
  289. public function getBreadcrumbs($action)
  290. {
  291. if($this->admin->isChild()) {
  292. return $this->admin->getParent()->getBreadcrumbs($action);
  293. }
  294. return $this->admin->getBreadcrumbs($action);
  295. }
  296. }