HelperController.php 19 KB

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