CRUDController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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\Security\Core\Exception\AccessDeniedException;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. class CRUDController extends Controller
  19. {
  20. /**
  21. * The related Admin class
  22. *
  23. * @var \Sonata\AdminBundle\Admin\AdminInterface
  24. */
  25. protected $admin;
  26. /**
  27. * @param mixed $data
  28. * @param integer $status
  29. * @param array $headers
  30. *
  31. * @return Response with json encoded data
  32. */
  33. public function renderJson($data, $status = 200, $headers = array())
  34. {
  35. // fake content-type so browser does not show the download popup when this
  36. // response is rendered through an iframe (used by the jquery.form.js plugin)
  37. // => don't know yet if it is the best solution
  38. if ($this->get('request')->get('_xml_http_request')
  39. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  40. $headers['Content-Type'] = 'text/plain';
  41. } else {
  42. $headers['Content-Type'] = 'application/json';
  43. }
  44. return new Response(json_encode($data), $status, $headers);
  45. }
  46. /**
  47. *
  48. * @return boolean true if the request is done by an ajax like query
  49. */
  50. public function isXmlHttpRequest()
  51. {
  52. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  53. }
  54. /**
  55. * Sets the Container associated with this Controller.
  56. *
  57. * @param ContainerInterface $container A ContainerInterface instance
  58. */
  59. public function setContainer(ContainerInterface $container = null)
  60. {
  61. $this->container = $container;
  62. $this->configure();
  63. }
  64. /**
  65. * Contextualize the admin class depends on the current request
  66. *
  67. * @throws \RuntimeException
  68. * @return void
  69. */
  70. public function configure()
  71. {
  72. $adminCode = $this->container->get('request')->get('_sonata_admin');
  73. if (!$adminCode) {
  74. throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $this->container->get('request')->get('_route')));
  75. }
  76. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  77. if (!$this->admin) {
  78. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  79. }
  80. $rootAdmin = $this->admin;
  81. if ($this->admin->isChild()) {
  82. $this->admin->setCurrentChild(true);
  83. $rootAdmin = $rootAdmin->getParent();
  84. }
  85. $rootAdmin->setRequest($this->container->get('request'));
  86. }
  87. /**
  88. * return the base template name
  89. *
  90. * @return string the template name
  91. */
  92. public function getBaseTemplate()
  93. {
  94. if ($this->isXmlHttpRequest()) {
  95. return $this->admin->getTemplate('ajax');
  96. }
  97. return $this->admin->getTemplate('layout');
  98. }
  99. /**
  100. * @param $view
  101. * @param array $parameters
  102. * @param null|\Symfony\Component\HttpFoundation\Response $response
  103. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response
  104. */
  105. public function render($view, array $parameters = array(), Response $response = null)
  106. {
  107. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  108. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  109. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  110. return parent::render($view, $parameters);
  111. }
  112. /**
  113. * return the Response object associated to the list action
  114. *
  115. * @return Response
  116. */
  117. public function listAction()
  118. {
  119. if (false === $this->admin->isGranted('LIST')) {
  120. throw new AccessDeniedException();
  121. }
  122. $datagrid = $this->admin->getDatagrid();
  123. $formView = $datagrid->getForm()->createView();
  124. // set the theme for the current Admin Form
  125. $this->get('twig')->getExtension('form')->setTheme($formView, $this->admin->getFilterTheme());
  126. return $this->render($this->admin->getListTemplate(), array(
  127. 'action' => 'list',
  128. 'form' => $formView,
  129. 'datagrid' => $datagrid
  130. ));
  131. }
  132. /**
  133. * execute a batch delete
  134. *
  135. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  136. * @param $query
  137. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  138. */
  139. public function batchActionDelete($query)
  140. {
  141. if (false === $this->admin->isGranted('DELETE')) {
  142. throw new AccessDeniedException();
  143. }
  144. $modelManager = $this->admin->getModelManager();
  145. try {
  146. $modelManager->batchDelete($this->admin->getClass(), $query);
  147. $this->get('session')->setFlash('sonata_flash_success', 'flash_batch_delete_success');
  148. } catch ( ModelManagerException $e ) {
  149. $this->get('session')->setFlash('sonata_flash_error', 'flash_batch_delete_error');
  150. }
  151. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  152. }
  153. /**
  154. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  155. * @param $id
  156. * @return \Symfony\Bundle\FrameworkBundle\Controller\Response|\Symfony\Component\HttpFoundation\RedirectResponse
  157. */
  158. public function deleteAction($id)
  159. {
  160. if (false === $this->admin->isGranted('DELETE')) {
  161. throw new AccessDeniedException();
  162. }
  163. $id = $this->get('request')->get($this->admin->getIdParameter());
  164. $object = $this->admin->getObject($id);
  165. if (!$object) {
  166. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  167. }
  168. if ($this->getRequest()->getMethod() == 'DELETE') {
  169. try {
  170. $this->admin->delete($object);
  171. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  172. } catch ( ModelManagerException $e ) {
  173. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  174. }
  175. return new RedirectResponse($this->admin->generateUrl('list'));
  176. }
  177. return $this->render('SonataAdminBundle:CRUD:delete.html.twig', array(
  178. 'object' => $object,
  179. 'action' => 'delete'
  180. ));
  181. }
  182. /**
  183. * return the Response object associated to the edit action
  184. *
  185. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  186. * @param $id
  187. * @return \Symfony\Component\HttpFoundation\Response
  188. */
  189. public function editAction($id = null)
  190. {
  191. if (false === $this->admin->isGranted('EDIT')) {
  192. throw new AccessDeniedException();
  193. }
  194. $id = $this->get('request')->get($this->admin->getIdParameter());
  195. $object = $this->admin->getObject($id);
  196. if (!$object) {
  197. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  198. }
  199. $this->admin->setSubject($object);
  200. $form = $this->admin->getForm();
  201. $form->setData($object);
  202. if ($this->get('request')->getMethod() == 'POST') {
  203. $form->bindRequest($this->get('request'));
  204. if ($form->isValid()) {
  205. $this->admin->update($object);
  206. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  207. if ($this->isXmlHttpRequest()) {
  208. return $this->renderJson(array(
  209. 'result' => 'ok',
  210. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  211. ));
  212. }
  213. // redirect to edit mode
  214. return $this->redirectTo($object);
  215. }
  216. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  217. }
  218. $view = $form->createView();
  219. // set the theme for the current Admin Form
  220. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  221. return $this->render($this->admin->getEditTemplate(), array(
  222. 'action' => 'edit',
  223. 'form' => $view,
  224. 'object' => $object,
  225. ));
  226. }
  227. /**
  228. * redirect the user depend on this choice
  229. *
  230. * @param $object
  231. * @return \Symfony\Component\HttpFoundation\Response
  232. */
  233. public function redirectTo($object)
  234. {
  235. $url = false;
  236. if ($this->get('request')->get('btn_update_and_list')) {
  237. $url = $this->admin->generateUrl('list');
  238. }
  239. if ($this->get('request')->get('btn_create_and_create')) {
  240. $url = $this->admin->generateUrl('create');
  241. }
  242. if (!$url) {
  243. $url = $this->admin->generateObjectUrl('edit', $object);
  244. }
  245. return new RedirectResponse($url);
  246. }
  247. /**
  248. * return the Response object associated to the batch action
  249. *
  250. * @throws \RuntimeException
  251. * @return \Symfony\Component\HttpFoundation\Response
  252. */
  253. public function batchAction()
  254. {
  255. if ($this->get('request')->getMethod() != 'POST') {
  256. throw new \RuntimeException('invalid request type, POST expected');
  257. }
  258. if ($data = json_decode($this->get('request')->get('data'), true)) {
  259. $action = $data['action'];
  260. $idx = $data['idx'];
  261. $all_elements = $data['all_elements'];
  262. } else {
  263. $action = $this->get('request')->get('action');
  264. $idx = $this->get('request')->get('idx');
  265. $all_elements = $this->get('request')->get('all_elements', false);
  266. }
  267. $batchActions = $this->admin->getBatchActions();
  268. if (!array_key_exists($action, $batchActions)) {
  269. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  270. }
  271. if (count($idx) == 0 && !$all_elements) { // no item selected
  272. $this->get('session')->setFlash('sonata_flash_info', 'flash_batch_empty');
  273. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  274. }
  275. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  276. if ($askConfirmation && $this->get('request')->get('confirmation') != 'ok') {
  277. $data = json_encode(array(
  278. 'action' => $action,
  279. 'idx' => $idx,
  280. 'all_elements' => $all_elements,
  281. ));
  282. $datagrid = $this->admin->getDatagrid();
  283. $formView = $datagrid->getForm()->createView();
  284. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  285. 'action' => 'list',
  286. 'datagrid' => $datagrid,
  287. 'form' => $formView,
  288. 'data' => $data,
  289. ));
  290. }
  291. // execute the action, batchActionXxxxx
  292. $action = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  293. $final_action = sprintf('batchAction%s', ucfirst($action));
  294. if (!method_exists($this, $final_action)) {
  295. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  296. }
  297. $datagrid = $this->admin->getDatagrid();
  298. $datagrid->buildPager();
  299. $query = $datagrid->getQuery();
  300. $query->setFirstResult(null);
  301. $query->setMaxResults(null);
  302. if (count($idx) > 0) {
  303. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  304. }
  305. return call_user_func(array($this, $final_action), $query);
  306. }
  307. /**
  308. * return the Response object associated to the create action
  309. *
  310. * @return \Symfony\Component\HttpFoundation\Response
  311. */
  312. public function createAction()
  313. {
  314. if (false === $this->admin->isGranted('CREATE')) {
  315. throw new AccessDeniedException();
  316. }
  317. $object = $this->admin->getNewInstance();
  318. $this->admin->setSubject($object);
  319. $form = $this->admin->getForm();
  320. $form->setData($object);
  321. if ($this->get('request')->getMethod() == 'POST') {
  322. $form->bindRequest($this->get('request'));
  323. if ($form->isValid()) {
  324. $this->admin->create($object);
  325. if ($this->isXmlHttpRequest()) {
  326. return $this->renderJson(array(
  327. 'result' => 'ok',
  328. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  329. ));
  330. }
  331. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  332. // redirect to edit mode
  333. return $this->redirectTo($object);
  334. }
  335. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  336. }
  337. $view = $form->createView();
  338. // set the theme for the current Admin Form
  339. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  340. return $this->render($this->admin->getEditTemplate(), array(
  341. 'action' => 'create',
  342. 'form' => $view,
  343. 'object' => $object,
  344. ));
  345. }
  346. /**
  347. * return the Response object associated to the view action
  348. *
  349. * @return \Symfony\Component\HttpFoundation\Response
  350. */
  351. public function showAction($id = null)
  352. {
  353. if (false === $this->admin->isGranted('SHOW')) {
  354. throw new AccessDeniedException();
  355. }
  356. $id = $this->get('request')->get($this->admin->getIdParameter());
  357. $object = $this->admin->getObject($id);
  358. if (!$object) {
  359. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  360. }
  361. $this->admin->setSubject($object);
  362. // build the show list
  363. $elements = $this->admin->getShow();
  364. return $this->render($this->admin->getShowTemplate(), array(
  365. 'action' => 'show',
  366. 'object' => $object,
  367. 'elements' => $this->admin->getShow(),
  368. ));
  369. }
  370. /**
  371. * @param null $id
  372. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  373. */
  374. public function historyAction($id = null)
  375. {
  376. if (false === $this->admin->isGranted('EDIT')) {
  377. throw new AccessDeniedException();
  378. }
  379. $id = $this->get('request')->get($this->admin->getIdParameter());
  380. $object = $this->admin->getObject($id);
  381. if (!$object) {
  382. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  383. }
  384. $manager = $this->get('sonata.admin.audit.manager');
  385. if (!$manager->hasReader($this->admin->getClass())) {
  386. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  387. }
  388. $reader = $manager->getReader($this->admin->getClass());
  389. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  390. return $this->render($this->admin->getTemplate('history'), array(
  391. 'action' => 'history',
  392. 'object' => $object,
  393. 'revisions' => $revisions,
  394. ));
  395. }
  396. /**
  397. * @param null $id
  398. * @param $revision
  399. */
  400. public function historyViewRevisionAction($id = null, $revision = null)
  401. {
  402. if (false === $this->admin->isGranted('EDIT')) {
  403. throw new AccessDeniedException();
  404. }
  405. $id = $this->get('request')->get($this->admin->getIdParameter());
  406. $object = $this->admin->getObject($id);
  407. if (!$object) {
  408. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  409. }
  410. $manager = $this->get('sonata.admin.audit.manager');
  411. if (!$manager->hasReader($this->admin->getClass())) {
  412. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  413. }
  414. $reader = $manager->getReader($this->admin->getClass());
  415. // retrieve the revisioned object
  416. $object = $reader->find($this->admin->getClass(), $id, $revision);
  417. if (!$object) {
  418. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  419. }
  420. $this->admin->setSubject($object);
  421. return $this->render($this->admin->getShowTemplate(), array(
  422. 'action' => 'show',
  423. 'object' => $object,
  424. 'elements' => $this->admin->getShow(),
  425. ));
  426. }
  427. }