CRUDController.php 11 KB

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