CRUDController.php 19 KB

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