CRUDController.php 11 KB

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