HelperController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project 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 Sonata\AdminBundle\Admin\AdminHelper;
  12. use Sonata\AdminBundle\Admin\AdminInterface;
  13. use Sonata\AdminBundle\Admin\Pool;
  14. use Sonata\AdminBundle\Filter\FilterInterface;
  15. use Symfony\Bridge\Twig\Form\TwigRenderer;
  16. use Symfony\Component\Form\FormInterface;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  21. use Symfony\Component\PropertyAccess\PropertyPath;
  22. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  23. use Symfony\Component\Validator\Validator\ValidatorInterface;
  24. use Symfony\Component\Validator\ValidatorInterface as LegacyValidatorInterface;
  25. /**
  26. * Class HelperController.
  27. *
  28. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  29. */
  30. class HelperController
  31. {
  32. /**
  33. * @var \Twig_Environment
  34. */
  35. protected $twig;
  36. /**
  37. * @var AdminHelper
  38. */
  39. protected $helper;
  40. /**
  41. * @var Pool
  42. */
  43. protected $pool;
  44. /**
  45. * @var ValidatorInterface|ValidatorInterface
  46. */
  47. protected $validator;
  48. /**
  49. * @param \Twig_Environment $twig
  50. * @param Pool $pool
  51. * @param AdminHelper $helper
  52. * @param ValidatorInterface $validator
  53. */
  54. public function __construct(\Twig_Environment $twig, Pool $pool, AdminHelper $helper, $validator)
  55. {
  56. if (!($validator instanceof ValidatorInterface) && !($validator instanceof LegacyValidatorInterface)) {
  57. throw new \InvalidArgumentException('Argument 4 is an instance of '.get_class($validator).', expecting an instance of \Symfony\Component\Validator\Validator\ValidatorInterface or \Symfony\Component\Validator\ValidatorInterface');
  58. }
  59. $this->twig = $twig;
  60. $this->pool = $pool;
  61. $this->helper = $helper;
  62. $this->validator = $validator;
  63. }
  64. /**
  65. * @throws NotFoundHttpException
  66. *
  67. * @param Request $request
  68. *
  69. * @return Response
  70. */
  71. public function appendFormFieldElementAction(Request $request)
  72. {
  73. $code = $request->get('code');
  74. $elementId = $request->get('elementId');
  75. $objectId = $request->get('objectId');
  76. $uniqid = $request->get('uniqid');
  77. $admin = $this->pool->getInstance($code);
  78. $admin->setRequest($request);
  79. if ($uniqid) {
  80. $admin->setUniqid($uniqid);
  81. }
  82. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  83. if ($objectId && !$subject) {
  84. throw new NotFoundHttpException();
  85. }
  86. if (!$subject) {
  87. $subject = $admin->getNewInstance();
  88. }
  89. $admin->setSubject($subject);
  90. list(, $form) = $this->helper->appendFormFieldElement($admin, $subject, $elementId);
  91. /* @var $form \Symfony\Component\Form\Form */
  92. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  93. // render the widget
  94. $renderer = $this->getFormRenderer();
  95. $renderer->setTheme($view, $admin->getFormTheme());
  96. return new Response($renderer->searchAndRenderBlock($view, 'widget'));
  97. }
  98. /**
  99. * @throws NotFoundHttpException
  100. *
  101. * @param Request $request
  102. *
  103. * @return Response
  104. */
  105. public function retrieveFormFieldElementAction(Request $request)
  106. {
  107. $code = $request->get('code');
  108. $elementId = $request->get('elementId');
  109. $objectId = $request->get('objectId');
  110. $uniqid = $request->get('uniqid');
  111. $admin = $this->pool->getInstance($code);
  112. $admin->setRequest($request);
  113. if ($uniqid) {
  114. $admin->setUniqid($uniqid);
  115. }
  116. if ($objectId) {
  117. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  118. if (!$subject) {
  119. throw new NotFoundHttpException(sprintf('Unable to find the object id: %s, class: %s', $objectId, $admin->getClass()));
  120. }
  121. } else {
  122. $subject = $admin->getNewInstance();
  123. }
  124. $admin->setSubject($subject);
  125. $formBuilder = $admin->getFormBuilder($subject);
  126. $form = $formBuilder->getForm();
  127. $form->handleRequest($request);
  128. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  129. // render the widget
  130. $renderer = $this->getFormRenderer();
  131. $renderer->setTheme($view, $admin->getFormTheme());
  132. return new Response($renderer->searchAndRenderBlock($view, 'widget'));
  133. }
  134. /**
  135. * @throws NotFoundHttpException|\RuntimeException
  136. *
  137. * @param Request $request
  138. *
  139. * @return Response
  140. */
  141. public function getShortObjectDescriptionAction(Request $request)
  142. {
  143. $code = $request->get('code');
  144. $objectId = $request->get('objectId');
  145. $uniqid = $request->get('uniqid');
  146. $linkParameters = $request->get('linkParameters', array());
  147. $admin = $this->pool->getInstance($code);
  148. if (!$admin) {
  149. throw new NotFoundHttpException();
  150. }
  151. $admin->setRequest($request);
  152. if ($uniqid) {
  153. $admin->setUniqid($uniqid);
  154. }
  155. if (!$objectId) {
  156. $objectId = null;
  157. }
  158. $object = $admin->getObject($objectId);
  159. if (!$object && 'html' == $request->get('_format')) {
  160. return new Response();
  161. }
  162. if ('json' == $request->get('_format')) {
  163. return new JsonResponse(array('result' => array(
  164. 'id' => $admin->id($object),
  165. 'label' => $admin->toString($object),
  166. )));
  167. } elseif ('html' == $request->get('_format')) {
  168. return new Response($this->twig->render($admin->getTemplate('short_object_description'), array(
  169. 'admin' => $admin,
  170. 'description' => $admin->toString($object),
  171. 'object' => $object,
  172. 'link_parameters' => $linkParameters,
  173. )));
  174. }
  175. throw new \RuntimeException('Invalid format');
  176. }
  177. /**
  178. * @param Request $request
  179. *
  180. * @return Response
  181. */
  182. public function setObjectFieldValueAction(Request $request)
  183. {
  184. $field = $request->get('field');
  185. $code = $request->get('code');
  186. $objectId = $request->get('objectId');
  187. $value = $request->get('value');
  188. $context = $request->get('context');
  189. $admin = $this->pool->getInstance($code);
  190. $admin->setRequest($request);
  191. // alter should be done by using a post method
  192. if (!$request->isXmlHttpRequest()) {
  193. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a XmlHttpRequest request header'));
  194. }
  195. if ($request->getMethod() != 'POST') {
  196. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a POST Request'));
  197. }
  198. $rootObject = $object = $admin->getObject($objectId);
  199. if (!$object) {
  200. return new JsonResponse(array('status' => 'KO', 'message' => 'Object does not exist'));
  201. }
  202. // check user permission
  203. if (false === $admin->isGranted('EDIT', $object)) {
  204. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid permissions'));
  205. }
  206. if ($context == 'list') {
  207. $fieldDescription = $admin->getListFieldDescription($field);
  208. } else {
  209. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid context'));
  210. }
  211. if (!$fieldDescription) {
  212. return new JsonResponse(array('status' => 'KO', 'message' => 'The field does not exist'));
  213. }
  214. if (!$fieldDescription->getOption('editable')) {
  215. return new JsonResponse(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true'));
  216. }
  217. $propertyPath = new PropertyPath($field);
  218. // If property path has more than 1 element, take the last object in order to validate it
  219. if ($propertyPath->getLength() > 1) {
  220. $object = $this->pool->getPropertyAccessor()->getValue($object, $propertyPath->getParent());
  221. $elements = $propertyPath->getElements();
  222. $field = end($elements);
  223. $propertyPath = new PropertyPath($field);
  224. }
  225. // Handle date type has setter expect a DateTime object
  226. if ('' !== $value && $fieldDescription->getType() == 'date') {
  227. $value = new \DateTime($value);
  228. }
  229. $this->pool->getPropertyAccessor()->setValue($object, $propertyPath, '' !== $value ? $value : null);
  230. $violations = $this->validator->validate($object);
  231. if (count($violations)) {
  232. $messages = array();
  233. foreach ($violations as $violation) {
  234. $messages[] = $violation->getMessage();
  235. }
  236. return new JsonResponse(array('status' => 'KO', 'message' => implode("\n", $messages)));
  237. }
  238. $admin->update($object);
  239. // render the widget
  240. // todo : fix this, the twig environment variable is not set inside the extension ...
  241. $extension = $this->twig->getExtension('Sonata\AdminBundle\Twig\Extension\SonataAdminExtension');
  242. $content = $extension->renderListElement($this->twig, $rootObject, $fieldDescription);
  243. return new JsonResponse(array('status' => 'OK', 'content' => $content));
  244. }
  245. /**
  246. * Retrieve list of items for autocomplete form field.
  247. *
  248. * @param Request $request
  249. *
  250. * @return JsonResponse
  251. *
  252. * @throws \RuntimeException
  253. * @throws AccessDeniedException
  254. */
  255. public function retrieveAutocompleteItemsAction(Request $request)
  256. {
  257. $admin = $this->pool->getInstance($request->get('admin_code'));
  258. $admin->setRequest($request);
  259. $context = $request->get('_context', '');
  260. if ($context === 'filter' && false === $admin->isGranted('LIST')) {
  261. throw new AccessDeniedException();
  262. }
  263. if ($context !== 'filter'
  264. && false === $admin->isGranted('CREATE')
  265. && false === $admin->isGranted('EDIT')
  266. ) {
  267. throw new AccessDeniedException();
  268. }
  269. // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
  270. $admin->setSubject($admin->getNewInstance());
  271. if ($context === 'filter') {
  272. // filter
  273. $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field'));
  274. $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName());
  275. $property = $filterAutocomplete->getFieldOption('property');
  276. $callback = $filterAutocomplete->getFieldOption('callback');
  277. $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3);
  278. $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10);
  279. $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page');
  280. $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback');
  281. } else {
  282. // create/edit form
  283. $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field'));
  284. $formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
  285. if ($formAutocomplete->getConfig()->getAttribute('disabled')) {
  286. throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.');
  287. }
  288. $property = $formAutocomplete->getConfig()->getAttribute('property');
  289. $callback = $formAutocomplete->getConfig()->getAttribute('callback');
  290. $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length');
  291. $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page');
  292. $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number');
  293. $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback');
  294. }
  295. $searchText = $request->get('q');
  296. $targetAdmin = $fieldDescription->getAssociationAdmin();
  297. // check user permission
  298. if (false === $targetAdmin->isGranted('LIST')) {
  299. throw new AccessDeniedException();
  300. }
  301. if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
  302. return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.'), 403);
  303. }
  304. $targetAdmin->setPersistFilters(false);
  305. $datagrid = $targetAdmin->getDatagrid();
  306. if ($callback !== null) {
  307. if (!is_callable($callback)) {
  308. throw new \RuntimeException('Callback does not contain callable function.');
  309. }
  310. call_user_func($callback, $targetAdmin, $property, $searchText);
  311. } else {
  312. if (is_array($property)) {
  313. // multiple properties
  314. foreach ($property as $prop) {
  315. if (!$datagrid->hasFilter($prop)) {
  316. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $prop, get_class($targetAdmin)));
  317. }
  318. $filter = $datagrid->getFilter($prop);
  319. $filter->setCondition(FilterInterface::CONDITION_OR);
  320. $datagrid->setValue($prop, null, $searchText);
  321. }
  322. } else {
  323. if (!$datagrid->hasFilter($property)) {
  324. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $property, get_class($targetAdmin)));
  325. }
  326. $datagrid->setValue($property, null, $searchText);
  327. }
  328. }
  329. $datagrid->setValue('_per_page', null, $itemsPerPage);
  330. $datagrid->setValue('_page', null, $request->query->get($reqParamPageNumber, 1));
  331. $datagrid->buildPager();
  332. $pager = $datagrid->getPager();
  333. $items = array();
  334. $results = $pager->getResults();
  335. foreach ($results as $entity) {
  336. if ($toStringCallback !== null) {
  337. if (!is_callable($toStringCallback)) {
  338. throw new \RuntimeException('Option "to_string_callback" does not contain callable function.');
  339. }
  340. $label = call_user_func($toStringCallback, $entity, $property);
  341. } else {
  342. $resultMetadata = $targetAdmin->getObjectMetadata($entity);
  343. $label = $resultMetadata->getTitle();
  344. }
  345. $items[] = array(
  346. 'id' => $admin->id($entity),
  347. 'label' => $label,
  348. );
  349. }
  350. return new JsonResponse(array(
  351. 'status' => 'OK',
  352. 'more' => !$pager->isLastPage(),
  353. 'items' => $items,
  354. ));
  355. }
  356. /**
  357. * Retrieve the form field description given by field name.
  358. *
  359. * @param AdminInterface $admin
  360. * @param string $field
  361. *
  362. * @return FormInterface
  363. *
  364. * @throws \RuntimeException
  365. */
  366. private function retrieveFormFieldDescription(AdminInterface $admin, $field)
  367. {
  368. $admin->getFormFieldDescriptions();
  369. $fieldDescription = $admin->getFormFieldDescription($field);
  370. if (!$fieldDescription) {
  371. throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
  372. }
  373. if (null === $fieldDescription->getTargetEntity()) {
  374. throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
  375. }
  376. return $fieldDescription;
  377. }
  378. /**
  379. * Retrieve the filter field description given by field name.
  380. *
  381. * @param AdminInterface $admin
  382. * @param string $field
  383. *
  384. * @return FormInterface
  385. *
  386. * @throws \RuntimeException
  387. */
  388. private function retrieveFilterFieldDescription(AdminInterface $admin, $field)
  389. {
  390. $admin->getFilterFieldDescriptions();
  391. $fieldDescription = $admin->getFilterFieldDescription($field);
  392. if (!$fieldDescription) {
  393. throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
  394. }
  395. if (null === $fieldDescription->getTargetEntity()) {
  396. throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
  397. }
  398. return $fieldDescription;
  399. }
  400. /**
  401. * @return TwigRenderer
  402. */
  403. private function getFormRenderer()
  404. {
  405. try {
  406. $runtime = $this->twig->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer');
  407. $runtime->setEnvironment($this->twig);
  408. return $runtime;
  409. } catch (\Twig_Error_Runtime $e) {
  410. // BC for Symfony < 3.2 where this runtime not exists
  411. $extension = $this->twig->getExtension('Symfony\Bridge\Twig\Extension\FormExtension');
  412. $extension->initRuntime($this->twig);
  413. return $extension->renderer;
  414. }
  415. }
  416. }