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