HelperController.php 17 KB

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