HelperController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 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\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  19. use Symfony\Component\PropertyAccess\PropertyAccess;
  20. use Symfony\Component\PropertyAccess\PropertyPath;
  21. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  22. use Symfony\Component\Validator\ValidatorInterface;
  23. /**
  24. * Class HelperController.
  25. *
  26. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  27. */
  28. class HelperController
  29. {
  30. /**
  31. * @var \Twig_Environment
  32. */
  33. protected $twig;
  34. /**
  35. * @var \Sonata\AdminBundle\Admin\AdminHelper
  36. */
  37. protected $helper;
  38. /**
  39. * @var \Sonata\AdminBundle\Admin\Pool
  40. */
  41. protected $pool;
  42. /**
  43. * @var \Symfony\Component\Validator\ValidatorInterface
  44. */
  45. protected $validator;
  46. /**
  47. * @param \Twig_Environment $twig
  48. * @param \Sonata\AdminBundle\Admin\Pool $pool
  49. * @param \Sonata\AdminBundle\Admin\AdminHelper $helper
  50. * @param \Symfony\Component\Validator\ValidatorInterface $validator
  51. */
  52. public function __construct(\Twig_Environment $twig, Pool $pool, AdminHelper $helper, ValidatorInterface $validator)
  53. {
  54. $this->twig = $twig;
  55. $this->pool = $pool;
  56. $this->helper = $helper;
  57. $this->validator = $validator;
  58. }
  59. /**
  60. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  61. *
  62. * @param \Symfony\Component\HttpFoundation\Request $request
  63. *
  64. * @return \Symfony\Component\HttpFoundation\Response
  65. */
  66. public function appendFormFieldElementAction(Request $request)
  67. {
  68. $code = $request->get('code');
  69. $elementId = $request->get('elementId');
  70. $objectId = $request->get('objectId');
  71. $uniqid = $request->get('uniqid');
  72. $admin = $this->pool->getInstance($code);
  73. $admin->setRequest($request);
  74. if ($uniqid) {
  75. $admin->setUniqid($uniqid);
  76. }
  77. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  78. if ($objectId && !$subject) {
  79. throw new NotFoundHttpException();
  80. }
  81. if (!$subject) {
  82. $subject = $admin->getNewInstance();
  83. }
  84. $admin->setSubject($subject);
  85. list(, $form) = $this->helper->appendFormFieldElement($admin, $subject, $elementId);
  86. /* @var $form \Symfony\Component\Form\Form */
  87. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  88. // render the widget
  89. // todo : fix this, the twig environment variable is not set inside the extension ...
  90. $extension = $this->twig->getExtension('form');
  91. $extension->initRuntime($this->twig);
  92. $extension->renderer->setTheme($view, $admin->getFormTheme());
  93. return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
  94. }
  95. /**
  96. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  97. *
  98. * @param \Symfony\Component\HttpFoundation\Request $request
  99. *
  100. * @return \Symfony\Component\HttpFoundation\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. // todo : fix this, the twig environment variable is not set inside the extension ...
  128. $extension = $this->twig->getExtension('form');
  129. $extension->initRuntime($this->twig);
  130. $extension->renderer->setTheme($view, $admin->getFormTheme());
  131. return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
  132. }
  133. /**
  134. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\RuntimeException
  135. *
  136. * @param \Symfony\Component\HttpFoundation\Request $request
  137. *
  138. * @return \Symfony\Component\HttpFoundation\Response
  139. */
  140. public function getShortObjectDescriptionAction(Request $request)
  141. {
  142. $code = $request->get('code');
  143. $objectId = $request->get('objectId');
  144. $uniqid = $request->get('uniqid');
  145. $linkParameters = $request->get('linkParameters', array());
  146. $admin = $this->pool->getInstance($code);
  147. if (!$admin) {
  148. throw new NotFoundHttpException();
  149. }
  150. $admin->setRequest($request);
  151. if ($uniqid) {
  152. $admin->setUniqid($uniqid);
  153. }
  154. if (!$objectId) {
  155. $objectId = null;
  156. }
  157. $object = $admin->getObject($objectId);
  158. if (!$object && 'html' == $request->get('_format')) {
  159. return new Response();
  160. }
  161. if ('json' == $request->get('_format')) {
  162. return new JsonResponse(array('result' => array(
  163. 'id' => $admin->id($object),
  164. 'label' => $admin->toString($object),
  165. )));
  166. } elseif ('html' == $request->get('_format')) {
  167. return new Response($this->twig->render($admin->getTemplate('short_object_description'), array(
  168. 'admin' => $admin,
  169. 'description' => $admin->toString($object),
  170. 'object' => $object,
  171. 'link_parameters' => $linkParameters,
  172. )));
  173. } else {
  174. throw new \RuntimeException('Invalid format');
  175. }
  176. }
  177. /**
  178. * @param \Symfony\Component\HttpFoundation\Request $request
  179. *
  180. * @return \Symfony\Component\HttpFoundation\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. $propertyAccessor = PropertyAccess::createPropertyAccessor();
  218. $propertyPath = new PropertyPath($field);
  219. // If property path has more than 1 element, take the last object in order to validate it
  220. if ($propertyPath->getLength() > 1) {
  221. $object = $propertyAccessor->getValue($object, $propertyPath->getParent());
  222. $elements = $propertyPath->getElements();
  223. $field = end($elements);
  224. $propertyPath = new PropertyPath($field);
  225. }
  226. $propertyAccessor->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_admin');
  239. $extension->initRuntime($this->twig);
  240. $content = $extension->renderListElement($rootObject, $fieldDescription);
  241. return new JsonResponse(array('status' => 'OK', 'content' => $content));
  242. }
  243. /**
  244. * Retrieve list of items for autocomplete form field.
  245. *
  246. * @param Request $request
  247. *
  248. * @return JsonResponse
  249. *
  250. * @throws \RuntimeException
  251. * @throws AccessDeniedException
  252. */
  253. public function retrieveAutocompleteItemsAction(Request $request)
  254. {
  255. $admin = $this->pool->getInstance($request->get('admin_code'));
  256. $admin->setRequest($request);
  257. $context = $request->get('_context', '');
  258. if ($context == 'filter' && false === $admin->isGranted('LIST')) {
  259. throw new AccessDeniedException();
  260. }
  261. if ($context != 'filter'
  262. && false === $admin->isGranted('CREATE')
  263. && false === $admin->isGranted('EDIT')
  264. ) {
  265. throw new AccessDeniedException();
  266. }
  267. // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
  268. $admin->setSubject($admin->getNewInstance());
  269. if ($context == 'filter') {
  270. // filter
  271. $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field'));
  272. $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName());
  273. $property = $filterAutocomplete->getFieldOption('property');
  274. $callback = $filterAutocomplete->getFieldOption('callback');
  275. $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3);
  276. $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10);
  277. $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page');
  278. $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback');
  279. } else {
  280. // create/edit form
  281. $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field'));
  282. $formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
  283. if ($formAutocomplete->getConfig()->getAttribute('disabled')) {
  284. throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.');
  285. }
  286. $property = $formAutocomplete->getConfig()->getAttribute('property');
  287. $callback = $formAutocomplete->getConfig()->getAttribute('callback');
  288. $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length');
  289. $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page');
  290. $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number');
  291. $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback');
  292. }
  293. $searchText = $request->get('q');
  294. $targetAdmin = $fieldDescription->getAssociationAdmin();
  295. // check user permission
  296. if (false === $targetAdmin->isGranted('LIST')) {
  297. throw new AccessDeniedException();
  298. }
  299. if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
  300. return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.'), 403);
  301. }
  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 \Symfony\Component\Form\FormInterface
  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 ($fieldDescription->getType() !== 'sonata_type_model_autocomplete') {
  371. throw new \RuntimeException(sprintf('Unsupported form type "%s" for field "%s".', $fieldDescription->getType(), $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 \Symfony\Component\Form\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. }