HelperController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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\Component\Form\FormInterface;
  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\PropertyAccess;
  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. // todo : fix this, the twig environment variable is not set inside the extension ...
  95. $extension = $this->twig->getExtension('form');
  96. $extension->initRuntime($this->twig);
  97. $extension->renderer->setTheme($view, $admin->getFormTheme());
  98. return new Response($extension->renderer->searchAndRenderBlock($view, 'widget'));
  99. }
  100. /**
  101. * @throws NotFoundHttpException
  102. *
  103. * @param Request $request
  104. *
  105. * @return Response
  106. */
  107. public function retrieveFormFieldElementAction(Request $request)
  108. {
  109. $code = $request->get('code');
  110. $elementId = $request->get('elementId');
  111. $objectId = $request->get('objectId');
  112. $uniqid = $request->get('uniqid');
  113. $admin = $this->pool->getInstance($code);
  114. $admin->setRequest($request);
  115. if ($uniqid) {
  116. $admin->setUniqid($uniqid);
  117. }
  118. if ($objectId) {
  119. $subject = $admin->getModelManager()->find($admin->getClass(), $objectId);
  120. if (!$subject) {
  121. throw new NotFoundHttpException(sprintf('Unable to find the object id: %s, class: %s', $objectId, $admin->getClass()));
  122. }
  123. } else {
  124. $subject = $admin->getNewInstance();
  125. }
  126. $admin->setSubject($subject);
  127. $formBuilder = $admin->getFormBuilder($subject);
  128. $form = $formBuilder->getForm();
  129. $form->handleRequest($request);
  130. $view = $this->helper->getChildFormView($form->createView(), $elementId);
  131. // render the widget
  132. // todo : fix this, the twig environment variable is not set inside the extension ...
  133. $extension = $this->twig->getExtension('form');
  134. $extension->initRuntime($this->twig);
  135. $extension->renderer->setTheme($view, $admin->getFormTheme());
  136. return new Response($extension->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. } else {
  179. throw new \RuntimeException('Invalid format');
  180. }
  181. }
  182. /**
  183. * @param Request $request
  184. *
  185. * @return Response
  186. */
  187. public function setObjectFieldValueAction(Request $request)
  188. {
  189. $field = $request->get('field');
  190. $code = $request->get('code');
  191. $objectId = $request->get('objectId');
  192. $value = $request->get('value');
  193. $context = $request->get('context');
  194. $admin = $this->pool->getInstance($code);
  195. $admin->setRequest($request);
  196. // alter should be done by using a post method
  197. if (!$request->isXmlHttpRequest()) {
  198. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a XmlHttpRequest request header'));
  199. }
  200. if ($request->getMethod() != 'POST') {
  201. return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a POST Request'));
  202. }
  203. $rootObject = $object = $admin->getObject($objectId);
  204. if (!$object) {
  205. return new JsonResponse(array('status' => 'KO', 'message' => 'Object does not exist'));
  206. }
  207. // check user permission
  208. if (false === $admin->isGranted('EDIT', $object)) {
  209. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid permissions'));
  210. }
  211. if ($context == 'list') {
  212. $fieldDescription = $admin->getListFieldDescription($field);
  213. } else {
  214. return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid context'));
  215. }
  216. if (!$fieldDescription) {
  217. return new JsonResponse(array('status' => 'KO', 'message' => 'The field does not exist'));
  218. }
  219. if (!$fieldDescription->getOption('editable')) {
  220. return new JsonResponse(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true'));
  221. }
  222. $propertyAccessor = PropertyAccess::createPropertyAccessor();
  223. $propertyPath = new PropertyPath($field);
  224. // If property path has more than 1 element, take the last object in order to validate it
  225. if ($propertyPath->getLength() > 1) {
  226. $object = $propertyAccessor->getValue($object, $propertyPath->getParent());
  227. $elements = $propertyPath->getElements();
  228. $field = end($elements);
  229. $propertyPath = new PropertyPath($field);
  230. }
  231. // Handle date type has setter expect a DateTime object
  232. if ('' !== $value && $fieldDescription->getType() == 'date') {
  233. $value = new \DateTime($value);
  234. }
  235. $propertyAccessor->setValue($object, $propertyPath, '' !== $value ? $value : null);
  236. $violations = $this->validator->validate($object);
  237. if (count($violations)) {
  238. $messages = array();
  239. foreach ($violations as $violation) {
  240. $messages[] = $violation->getMessage();
  241. }
  242. return new JsonResponse(array('status' => 'KO', 'message' => implode("\n", $messages)));
  243. }
  244. $admin->update($object);
  245. // render the widget
  246. // todo : fix this, the twig environment variable is not set inside the extension ...
  247. $extension = $this->twig->getExtension('sonata_admin');
  248. $extension->initRuntime($this->twig);
  249. $content = $extension->renderListElement($rootObject, $fieldDescription);
  250. return new JsonResponse(array('status' => 'OK', 'content' => $content));
  251. }
  252. /**
  253. * Retrieve list of items for autocomplete form field.
  254. *
  255. * @param Request $request
  256. *
  257. * @return JsonResponse
  258. *
  259. * @throws \RuntimeException
  260. * @throws AccessDeniedException
  261. */
  262. public function retrieveAutocompleteItemsAction(Request $request)
  263. {
  264. $admin = $this->pool->getInstance($request->get('admin_code'));
  265. $admin->setRequest($request);
  266. $context = $request->get('_context', '');
  267. if ($context === 'filter' && false === $admin->isGranted('LIST')) {
  268. throw new AccessDeniedException();
  269. }
  270. if ($context !== 'filter'
  271. && false === $admin->isGranted('CREATE')
  272. && false === $admin->isGranted('EDIT')
  273. ) {
  274. throw new AccessDeniedException();
  275. }
  276. // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
  277. $admin->setSubject($admin->getNewInstance());
  278. if ($context === 'filter') {
  279. // filter
  280. $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field'));
  281. $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName());
  282. $property = $filterAutocomplete->getFieldOption('property');
  283. $callback = $filterAutocomplete->getFieldOption('callback');
  284. $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3);
  285. $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10);
  286. $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page');
  287. $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback');
  288. } else {
  289. // create/edit form
  290. $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field'));
  291. $formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
  292. if ($formAutocomplete->getConfig()->getAttribute('disabled')) {
  293. throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.');
  294. }
  295. $property = $formAutocomplete->getConfig()->getAttribute('property');
  296. $callback = $formAutocomplete->getConfig()->getAttribute('callback');
  297. $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length');
  298. $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page');
  299. $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number');
  300. $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback');
  301. }
  302. $searchText = $request->get('q');
  303. $targetAdmin = $fieldDescription->getAssociationAdmin();
  304. // check user permission
  305. if (false === $targetAdmin->isGranted('LIST')) {
  306. throw new AccessDeniedException();
  307. }
  308. if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
  309. return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.'), 403);
  310. }
  311. $targetAdmin->setPersistFilters(false);
  312. $datagrid = $targetAdmin->getDatagrid();
  313. if ($callback !== null) {
  314. if (!is_callable($callback)) {
  315. throw new \RuntimeException('Callback does not contain callable function.');
  316. }
  317. call_user_func($callback, $targetAdmin, $property, $searchText);
  318. } else {
  319. if (is_array($property)) {
  320. // multiple properties
  321. foreach ($property as $prop) {
  322. if (!$datagrid->hasFilter($prop)) {
  323. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $prop, get_class($targetAdmin)));
  324. }
  325. $filter = $datagrid->getFilter($prop);
  326. $filter->setCondition(FilterInterface::CONDITION_OR);
  327. $datagrid->setValue($prop, null, $searchText);
  328. }
  329. } else {
  330. if (!$datagrid->hasFilter($property)) {
  331. throw new \RuntimeException(sprintf('To retrieve autocomplete items, you should add filter "%s" to "%s" in configureDatagridFilters() method.', $property, get_class($targetAdmin)));
  332. }
  333. $datagrid->setValue($property, null, $searchText);
  334. }
  335. }
  336. $datagrid->setValue('_per_page', null, $itemsPerPage);
  337. $datagrid->setValue('_page', null, $request->query->get($reqParamPageNumber, 1));
  338. $datagrid->buildPager();
  339. $pager = $datagrid->getPager();
  340. $items = array();
  341. $results = $pager->getResults();
  342. foreach ($results as $entity) {
  343. if ($toStringCallback !== null) {
  344. if (!is_callable($toStringCallback)) {
  345. throw new \RuntimeException('Option "to_string_callback" does not contain callable function.');
  346. }
  347. $label = call_user_func($toStringCallback, $entity, $property);
  348. } else {
  349. $resultMetadata = $targetAdmin->getObjectMetadata($entity);
  350. $label = $resultMetadata->getTitle();
  351. }
  352. $items[] = array(
  353. 'id' => $admin->id($entity),
  354. 'label' => $label,
  355. );
  356. }
  357. return new JsonResponse(array(
  358. 'status' => 'OK',
  359. 'more' => !$pager->isLastPage(),
  360. 'items' => $items,
  361. ));
  362. }
  363. /**
  364. * Retrieve the form field description given by field name.
  365. *
  366. * @param AdminInterface $admin
  367. * @param string $field
  368. *
  369. * @return FormInterface
  370. *
  371. * @throws \RuntimeException
  372. */
  373. private function retrieveFormFieldDescription(AdminInterface $admin, $field)
  374. {
  375. $admin->getFormFieldDescriptions();
  376. $fieldDescription = $admin->getFormFieldDescription($field);
  377. if (!$fieldDescription) {
  378. throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
  379. }
  380. if (null === $fieldDescription->getTargetEntity()) {
  381. throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
  382. }
  383. return $fieldDescription;
  384. }
  385. /**
  386. * Retrieve the filter field description given by field name.
  387. *
  388. * @param AdminInterface $admin
  389. * @param string $field
  390. *
  391. * @return FormInterface
  392. *
  393. * @throws \RuntimeException
  394. */
  395. private function retrieveFilterFieldDescription(AdminInterface $admin, $field)
  396. {
  397. $admin->getFilterFieldDescriptions();
  398. $fieldDescription = $admin->getFilterFieldDescription($field);
  399. if (!$fieldDescription) {
  400. throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
  401. }
  402. if (null === $fieldDescription->getTargetEntity()) {
  403. throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
  404. }
  405. return $fieldDescription;
  406. }
  407. }