HelperController.php 17 KB

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